我试图使用javascript的拆分来获取字符串中的句子,但保留分隔符,例如!?.
到目前为止我有
sentences = text.split(/[\\.!?]/);
Run Code Online (Sandbox Code Playgroud)
哪个有效,但不包括每个句子的结尾标点符号(.!?).
有谁知道这样做的方法?
目前我正在开发一个将长列分成短列的应用程序.为此我将整个文本分成单词,但此刻我的正则表达式也将数字拆分.
我这样做是这样的:
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)
我如何改变我的正则表达式来实现这一目标?我是否需要注意可能遇到的一些问题?或者它是否足以搜索". ","? "并且"! " …
我在使用 javascript 的正则表达式时遇到了一些困难;
这是我的小提琴:http : //jsfiddle.net/6yhwzap0/
我创建的函数是:
var splitSentences = function(text) {
var messy = text.match(/\(?[^\.\?\!]+[\.!\?]\)?/g);
var clean = [];
for(var i = 0; i < messy.length; i++) {
var s = messy[i];
var sTrimmed = s.trim();
if(sTrimmed.length > 0) {
if(sTrimmed.indexOf(' ') >= 0) {
clean.push(sTrimmed);
} else {
var d = clean[clean.length - 1];
d = d + s;
var e = messy[i + 1];
if(e.trim().indexOf(' ') >= 0) {
d = d + e;
i++;
} …Run Code Online (Sandbox Code Playgroud)