2019-09-16
Regex. Replace particular characters in string
stackoverflow
Question

In the following string i need to replace (with Regex only) all _ with the dots, except ones that are surrounded by digits. So this:

_this_is_a_2_2_replacement_

Should become

.this.is.a.2_2.replacement.

Tried lots of things. That's where i got so far:

([a-z]*(_)[a-z]*(_))*(?=\d_\d)...(_)\w*(_)

But it obviously doesn't work.

Answer
1

Try finding the following regex pattern:

(?<=\D)_|_(?=\D)

And then just replace that with dot. The logic here is that a replacement happens whenever an underscore which has at least one non digit on either side gets replaced with a dot. The regex pattern I used here asserts precisely this:

(?<=\D)_    an underscore preceded by a non digit
|           OR
_(?=\D)     an underscore followed by a non digit

Demo

Regex. Replace particular characters in string
See more ...