【问题标题】:Splitting by word boundaries including apostrophes按单词边界(包括撇号)拆分
【发布时间】:2020-06-03 03:23:33
【问题描述】:

我想将字符串中的每个单词(包括空格和标点符号)分成不同的组,但我想将带撇号的单词放在一起。

例如:

Phrase: This is right.
Groups: [This] [ ] [is] [ ] [right] [.]

Phrase: This isn't right.
Groups: [This] [ ] [isn't] [ ] [right] [.]

Phrase: "I said ok."
Groups: ["] [I] [ ] [said] [ ] [ok] [.] ["]

我正在使用正则表达式:str.split(/(?=[.,"\s]|\b)/)

但是,这不适用于撇号。对于阶段:这是不对的。,它像这样分裂:

[This] [ ] [isn] ['] [t] [ ] [right] [.]

有没有办法让不是在一个组中?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    我会改用.match:匹配一个单词字符后跟(单词字符或撇号)(\w[\w']*),或匹配空格:+,或匹配其他标点符号([.,"]):

    \w[\w']*| +|[.,"]
    

    https://regex101.com/r/B755JA/1

    const inputs = `This is right.
    This isn't right.
    "I said ok."`.split('\n');
    for (const input of inputs) {
      console.log(input.match(/\w[\w']*| +|[.,"]/g));
    }

    【讨论】:

      【解决方案2】:

      您可以尝试查找模式 [A-Za-z']+|[^A-Za-z'] 上的所有正则表达式匹配项,该模式匹配单词(字母或撇号)或单个非单词字符。

      var regex = /[A-Za-z']+|[^A-Za-z']/g;
      var input = "\"This isn't right.\"";
      var m;
      var matches = [];
      
      var i = 0;
      do {
          m = regex.exec(input);
          if (m) {
              matches[i] = m[0];
              ++i;
          }
      } while (m);
      
      console.log(matches);

      请注意,使用直接正则表达式查找所有方法有时比更复杂的正则表达式拆分逻辑更可取。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-10
        • 2016-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多