【问题标题】:RegExp / JavaScript: Split string on multiple characters, keep separators without using lookbehindRegExp / JavaScript:在多个字符上拆分字符串,保留分隔符而不使用lookbehind
【发布时间】:2021-10-26 20:16:34
【问题描述】:

假设我有一个字符串:"This is a string-thing"。我想拆分空格和连字符,但将分隔符与前一个单词保持在一起 => ["This ", "is ", "a ", "string-", "thing"]

我目前正在使用以下正则表达式:

string.split(/(?<=[\s-])/g)

这是应该做的......至少在 Chrome 中。据我了解,Safari 不支持 regExp 中的lookbehind,这会破坏代码。有什么方法可以做到这一点而无需向后看?

【问题讨论】:

    标签: javascript arrays regex string split


    【解决方案1】:

    您可以匹配单词而无需后视。

    const
        string = "This is a string-thing",
        parts = string.match(/.+?([\s-]|$)/g);
    
    console.log(parts);

    【讨论】:

      【解决方案2】:

      您还可以将 split 与捕获组一起使用以保留要拆分的值,并从结果数组中删除空条目。

      模式匹配

      • ( 捕获第一组
        • [^\s-]* 重复 0+ 次匹配除空白字符或 - 以外的任何字符
        • [\s-] 匹配空格字符或-
      • )关闭第一组

      注意\s 也可以匹配换行符。

      const s = "This is a string-thing";
      const regex = /([^\s-]*[\s-])/;
      console.log(s.split(regex).filter(Boolean));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        相关资源
        最近更新 更多