![](/img/trans.png)
[英]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.