Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

javascript - Split string into sentences - ignoring abbreviations for splitting

I'm trying to split this string into sentences, but I need to handle abbreviations (which have the fixed format x.y. as a word:

content = "This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn't split the sentence. Sometimes there are problems, i.e. in this one. here and abbr at the end x.y.. cool."

I tried this regex:

content.replace(/([.?!])s+(?=[A-Za-z])/g, "$1|").split("|");

But as you can see there are problems with abbreviations. As all the abbreviations are of the format x.y. it should be possible to handle them as a word, without splitting the string at this point.

"This is a long string with some numbers 123.456,78 or 100.000 and e.g.", 
"some abbreviations in it, which shouldn't split the sentence."
"Sometimes there are problems, i.e.", 
"in this one.", 
"here and abbr at the end x.y..",
"cool."

The result should be:

"This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn't split the sentence."
"Sometimes there are problems, i.e. in this one.", 
"here and abbr at the end x.y..",
"cool."
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution is to match and capture the abbreviations and build the replacement using a callback:

var re = /(w.w.)|([.?!])s+(?=[A-Za-z])/g; 
var str = 'This is a long string with some numbers 123.456,78 or 100.000 and e.g. some abbreviations in it, which shouldn't split the sentence. Sometimes there are problems, i.e. in this one. here and abbr at the end x.y.. cool.';
var result = str.replace(re, function(m, g1, g2){
  return g1 ? g1 : g2+"
";
});
var arr = result.split("
");
document.body.innerHTML = "<pre>" + JSON.stringify(arr, 0, 4) + "</pre>";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...