Reputation: 436
Hello I need to replace only single occurrence of substring Example:
Some sentence #x;#x;#x; with #x;#x; some #x; words #x; need in replacing.
Need replace only single #x; by #y; and get following string
Some sentence #x;#x;#x; with #x;#x; some #y; words #y; need in replacing.
Some note: My string will contain unicode chars and operator \b doesn't work.
Upvotes: 1
Views: 1553
Reputation: 4564
A single #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' )
Upvotes: 1
Reputation: 700552
You can match #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;
});
Upvotes: 2
Reputation: 838696
The simplest regular expression to match single occurences of #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:
/(^[\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."
Upvotes: 2