admin管理员组文章数量:1392054
Using JavaScript I'm trying to split a paragraph into it's sentences using regular expressions. My regular expression doesn't account for a sentence being inside brackets and I would like to keep the delimiter.
I've put an example of the code in jsFiddle here
Using JavaScript I'm trying to split a paragraph into it's sentences using regular expressions. My regular expression doesn't account for a sentence being inside brackets and I would like to keep the delimiter.
I've put an example of the code in jsFiddle here
Share Improve this question edited Jun 27, 2012 at 15:50 pb2q 59.7k19 gold badges150 silver badges152 bronze badges asked Jun 27, 2012 at 15:46 Mike MengellMike Mengell 2,3982 gold badges21 silver badges35 bronze badges 1- Does this answer your question? Javascript and regex: split string and keep the separator – Liam Commented May 12, 2023 at 11:35
3 Answers
Reset to default 4I took the match approach rather than split. It could be tighter (e.g. what if a sentence ends with ...
, etc).
text.match(/\(?[A-Z][^\.]+[\.!\?]\)?(\s+|$)/g);
http://jsfiddle/DepKF/1/
@Utkanos You idea is good, but I think replace
may better:
text.replace(/\(?[A-Z][^\.]+[\.!\?]\)?/g, function (sentence) {
output += '<p>'+ sentence + '</p>';
});
http://jsfiddle/juGT7/1/
You no need to loop again.
use the (?=pattern) lookahead pattern in the regex example
var string = '500x500-11*90~1+1';
string = string.replace(/(?=[$-/:-?{-~!"^_`\[\]])/gi, ",");
string = string.split(",");
this will give you the following result.
[ '500x500', '-11', '*90', '~1', '+1' ]
Can also be directly split
string = string.split(/(?=[$-/:-?{-~!"^_`\[\]])/gi);
giving the same result
[ '500x500', '-11', '*90', '~1', '+1' ]
本文标签: regexJavaScript Split Regular Expression keep the delimiterStack Overflow
版权声明:本文标题:regex - JavaScript Split Regular Expression keep the delimiter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744782415a2624791.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论