正则表达式最大值后拆分而不会丢失分隔线

时间:2019-02-17 21:06:08

标签: javascript regex

我想将字符串转换为: 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 个答案:

答案 0 :(得分:3)

不确定真正的要求,但是要实现所需的功能,可以使用.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

答案 1 :(得分:0)

一种解决方案可能是首先使用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));

相关问题