[英]RegExp: Match only single substring occurrence
Hello I need to replace only single occurrence of substring Example: 您好,我只需要替换单个出现的子字符串示例:
Some sentence #x;#x;#x ; 一些句子#x; #x; #x ; with #x;#x; 与#x; #x; some #x; 一些#x; words #x; 单词#x; need in replacing. 需要更换。
Need replace only single #x; 只需要替换单个#x; by #y; 由#y; and get following string 并获得以下字符串
Some sentence #x;#x;#x; 一些句子#x; #x; #x; with #x;#x; 与#x; #x; some #y; 一些#y; words #y; #y; need in replacing. 需要更换。
Some note: My string will contain unicode chars and operator \\b doesn't work. 注意:我的字符串将包含Unicode字符,并且运算符\\ b不起作用。
The simplest regular expression to match single occurences of #x;
最简单的正则表达式,用于匹配#x;
only would be to use a lookbehind and a lookahead assertion. 唯一的办法就是使用先行后断和先行断言。
/(?<!#x;)#x;(?!#x;)/
However Javascript does not support lookbehinds so you can try this workaround using only lookaheads instead: 但是,Javascript不支持lookbehinds,因此您可以尝试仅使用lookaheads来尝试此替代方法:
/(^[\S\s]{0,2}|(?!#x;)[\S\s]{3})#x;(?!#x;)/
Complete example: 完整的例子:
> 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."
You can match #x; 您可以匹配#x; repeated any number of times, and only replace those where it occurs once: 重复任意次,仅替换一次:
sentence = sentence.replace(/((?:#x;)+)/g, function(m) {
return m.length == 3 ? '#y;' : m;
});
A single #x;
单个#x;
could qualify by having white-space before and after. 可以通过前后有空格来限定。 In this case you could use this: 在这种情况下,您可以使用以下方法:
str.replace( /(\s+)#x;(\s+)/g, '$1#y;$2' )
使用str.replace('/(#x;)+/g','#y;')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.