【问题标题】:How to split text into words while only capturing full stops and spaces that come after full stops?如何将文本拆分为单词,同时仅捕获句号和句号之后的空格?
【发布时间】:2021-01-10 05:46:21
【问题描述】:

我想拆分这段文字,

"Tom works. Tom is a student. Bob is a student."

进入这个,

["Tom", "works", ".", " ", "Tom", "is", "a", "student", ".", " ", "Bob", "is", "a", "student", "."]

我尝试过text.split(/(\.)(\s)/),但我不确定如何在不捕获空格的情况下添加分割。

【问题讨论】:

    标签: javascript regex capturing-group


    【解决方案1】:

    您可以在未捕获的空格上拆分,在捕获的时段可选地捕获的空间,然后过滤掉空匹配:

    console.log(
      "Tom works. Tom is a student. Bob is a student."
        .split(/ |(\.)(\s)?/)
        .filter(Boolean)
    );

    另一种方法,用.match 代替split,并使用lookbehind:

    console.log(
      "Tom works. Tom is a student. Bob is a student."
        .match(/[^\s.]+|\.|(?<=\.) /g)
    );

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      相关资源
      最近更新 更多