[英]Validate a string that only contains a single occurrence of some specific substring
[英]RegExp: Match only single substring occurrence
您好,我只需要替换单个出现的子字符串示例:
一些句子#x; #x; #x ; 与#x; #x; 一些#x; 单词#x; 需要更换。
只需要替换单个#x; 由#y; 并获得以下字符串
一些句子#x; #x; #x; 与#x; #x; 一些#y; #y; 需要更换。
注意:我的字符串将包含Unicode字符,并且运算符\\ b不起作用。
最简单的正则表达式,用于匹配#x;
唯一的办法就是使用先行后断和先行断言。
/(?<!#x;)#x;(?!#x;)/
但是,Javascript不支持lookbehinds,因此您可以尝试仅使用lookaheads来尝试此替代方法:
/(^[\S\s]{0,2}|(?!#x;)[\S\s]{3})#x;(?!#x;)/
完整的例子:
> s = 'Some sentence #x;#x;#x; with #x;#x; some #x; words #x; need in replacing.'
> s = s.replace(/(^[\S\s]{0,2}|(?!#x;)[\S\s]{3})#x;(?!#x;)/g, '$1#y;')
"Some sentence #x;#x;#x; with #x;#x; some #y; words #y; need in replacing."
您可以匹配#x; 重复任意次,仅替换一次:
sentence = sentence.replace(/((?:#x;)+)/g, function(m) {
return m.length == 3 ? '#y;' : m;
});
单个#x;
可以通过前后有空格来限定。 在这种情况下,您可以使用以下方法:
str.replace( /(\s+)#x;(\s+)/g, '$1#y;$2' )
使用str.replace('/(#x;)+/g','#y;')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.