Alvin K.
Alvin K.

Reputation: 4379

Changing n-th occurrence with regex

With reference to this SO question: Cutting a string at nth occurrence of a character

Have a slightly different question: Can this be done using regex?

"aa.bb.cc.dd.ee.xx" => "aa.bb.NN.dd.ee.ff" 
(replacing only 3rd occurrence, all chars are random alphanumeric text )

NOTE: .split() .slice() .join() is a readable solution, regex seems possible and straightforward (I may be wrong). Eg: replacing the first two "aa." and "bb." with say 'AoA' and 'BoB', seems trivial:-

`"aa.bb.cc.dd.ee.xx".replace(/([^\.]*\.){2}/, 'AoA.BoB.')`

Edit: Since "." means 'matching anything' in regex, please use ";" (semicolon) instead. To make it more difficult, what if we have a string like this:

"ax;;cyz;def;eghi;xyzw" and we wanted to replace 3rd section (eg: cyz)

Upvotes: 2

Views: 115

Answers (3)

sshashank124
sshashank124

Reputation: 32189

To replace the 3rd occurence, you would match:

^((\w{2}\.){2})\w{2}\.(.*)$

and replace with:

\1NN.\3

To replace the n-th occurence, you would match:

^((\w{2}\.){n-1})\w{2}\.(.*)$

Demo

For your comment:

^(([^;]*\;){2})[^;]*\;(.*)$

Demo2

Upvotes: 3

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12797

You can use the following regex and replace it with $1Hello$3. n-1 => 2.

^((?:[^;]*;){2})([^;]*)(.*)$

Regular expression visualization

Demo

Upvotes: 2

hwnd
hwnd

Reputation: 70722

For this specific string instance, you could also use the following.

[^.]*(?=(?:\.[^.]*){3}$)

Regular expression

[^.]*           any character except: '.' (0 or more times)
(?=             look ahead to see if there is:
 (?:            group, but do not capture (3 times):
 \.             '.'
  [^.]*         any character except: '.' (0 or more times)
){3}            end of grouping
 $              before an optional \n, and the end of the string
)               end of look-ahead

See Live demo

Upvotes: 2

Related Questions