Ilya
Ilya

Reputation: 436

RegExp: Match only single substring occurrence

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

Answers (4)

bw_üezi
bw_üezi

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

xkeshav
xkeshav

Reputation: 54052

use str.replace('/(#x;)+/g','#y;')

Upvotes: 0

Guffa
Guffa

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

Mark Byers
Mark Byers

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

Related Questions