目前我正在开发一个将长列分成短列的应用程序.为此我将整个文本分成单词,但此刻我的正则表达式也将数字拆分.
我这样做是这样的:
str = "This is a long string with some numbers [125.000,55 and 140.000] and an end. This is another sentence.";
sentences = str.replace(/\.+/g,'.|').replace(/\?/g,'?|').replace(/\!/g,'!|').split("|");
Run Code Online (Sandbox Code Playgroud)
结果是:
Array [
"This is a long string with some numbers [125.",
"000,55 and 140.",
"000] and an end.",
" This is another sentence."
]
Run Code Online (Sandbox Code Playgroud)
期望的结果是:
Array [
"This is a long string with some numbers [125.000, 140.000] and an end.",
"This is another sentence"
]
Run Code Online (Sandbox Code Playgroud)
我如何改变我的正则表达式来实现这一目标?我是否需要注意可能遇到的一些问题?或者它是否足以搜索". "
,"? "
并且"! "
?
小智 29
str.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|")
Run Code Online (Sandbox Code Playgroud)
输出:
[ 'This is a long string with some numbers [125.000,55 and 140.000] and an end.',
'This is another sentence.' ]
Run Code Online (Sandbox Code Playgroud)
分解:
([.?!])
=捕获.
或?
或!
\s*
=在前一个标记后面捕获0个或多个空格字符([.?!])
.这解释了与英语语法匹配的标点符号后面的空格.
(?=[A-Z])
=如果下一个字符在AZ(大写字母A到大写字母Z)的范围内,则前一个标记仅匹配.大多数英语语句以大写字母开头.以前的正则表达都没有考虑到这一点.
替换操作使用:
"$1|"
Run Code Online (Sandbox Code Playgroud)
我们使用了一个"捕获组" ([.?!])
,我们捕获其中一个字符,并用$1
(匹配)加上替换它|
.因此,如果我们捕获,?
则替换将是?|
.
最后,我们拆分管道|
并获得结果.
所以,基本上,我们所说的是:
1)找到标点符号(一个.
或?
或!
)和捕捉他们
2)标点符号可以选择在它们之后包含空格.
3)标点符号后,我希望有一个大写字母.
与之前提供的正则表达式不同,这将与英语语法完全匹配.
从那里:
4)我们通过附加管道替换捕获的标点符号 |
5)我们拆分管道以创建一系列句子.
str.replace(/(\.+|\:|\!|\?)(\"*|\'*|\)*|}*|]*)(\s|\n|\r|\r\n)/gm, "$1$2|").split("|")
Run Code Online (Sandbox Code Playgroud)
RegExp(参见Debuggex):
备注:
您可以利用下一句以大写字母或数字开头.
.*?(?:\.|!|\?)(?:(?= [A-Z0-9])|$)
Run Code Online (Sandbox Code Playgroud)
它拆分了这个文本
This is a long string with some numbers [125.000,55 and 140.000] and an end. This is another sentence. Sencenes beginning with numbers work. 10 people like that.
Run Code Online (Sandbox Code Playgroud)
进入句子:
This is a long string with some numbers [125.000,55 and 140.000] and an end.
This is another sentence.
Sencenes beginning with numbers work.
10 people like that.
Run Code Online (Sandbox Code Playgroud)
如果后面没有空格 + 字符字符,请使用前瞻来避免替换点:
sentences = str.replace(/(?=\s*\w)\./g,'.|').replace(/\?/g,'?|').replace(/\!/g,'!|').split("|");
Run Code Online (Sandbox Code Playgroud)
输出:
["This is a long string with some numbers [125.000,55 and 140.000] and an end. This is another sentence."]
Run Code Online (Sandbox Code Playgroud)