代码之家  ›  专栏  ›  技术社区  ›  iRyanBell

在不丢失delimeter的情况下在regex max之后拆分

  •  0
  • iRyanBell  · 技术社区  · 7 年前

    我想转换一个字符串,如下所示: hello!world.what?up 进入 ["hello!", "world.", "what?", "up"]

    .split(/[?=<\.\?\!>]+/) 接近于我所追求的,返回:

    ["hello", "world", "what", "up"]

    .split(/(?=[\?\!\.])/) 更近一点,返回:

    ["hello", "!world", ".what", "?up"]

    这是个好办法,但并不漂亮:

    .split(/(?=[\?\!\.])/).map((s, idx, arr) => { (idx > 0) s = s.slice(1); return idx < arr.length - 1 ? s + arr[idx+1][0] : s }).filter(s => s)

    编辑:更新的问题。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Gabriele Petrioli    7 年前

    不确定真正的需求,但要实现您想要的,您可以使用 .match 而不是 .split .

    const items =
      'hello!world.what?'.match(/\w+\W/g);
    
    console.log(items);

    enter image description here


    评论后更新

    const items =
      'hello!world.what?'.match(/\w+[!.?]/g);
    
    console.log(items);

    enter image description here


    补充更新

    前面的解决方案将只选择 !.? 如果要匹配除分隔符之外的任何字符,请使用

    const items =
      'hello!world.what?up'.match(/[^!.?]+([!.?]|$)/g);
    
    console.log(items);

    enter image description here

        2
  •  0
  •   Shidersz    7 年前

    一种解决方案可能是首先使用的 replace() 对于在每个搜索的字符后添加标记,则可以按此标记拆分。

    let input = "hello!world.what?";
    
    const customSplit = (str) =>
    {
        let token = "#";
        return str.replace(/[!.?]/g, (match) => match + "#")
            .split(token)
            .filter(Boolean);
    }
    
    console.log(customSplit(input));