如何在仅捕获句号和句号后的空格的同时将文本拆分为单词?
How to split text into words while only capturing full stops and spaces that come after full stops?
我想拆分这段文字,
"Tom works. Tom is a student. Bob is a student."
进入这个,
["Tom", "works", ".", " ", "Tom", "is", "a", "student", ".", " ", "Bob", "is", "a", "student", "."]
我试过 text.split(/(\.)(\s)/)
但我不确定如何在不捕获空间的情况下添加空间分割。
您可以在 non-captured space 秒、 或 捕获周期 and 可选地捕获 space,然后过滤掉空匹配:
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)
);
我想拆分这段文字,
"Tom works. Tom is a student. Bob is a student."
进入这个,
["Tom", "works", ".", " ", "Tom", "is", "a", "student", ".", " ", "Bob", "is", "a", "student", "."]
我试过 text.split(/(\.)(\s)/)
但我不确定如何在不捕获空间的情况下添加空间分割。
您可以在 non-captured space 秒、 或 捕获周期 and 可选地捕获 space,然后过滤掉空匹配:
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)
);