2

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.

Alex Smoke
  • 619
  • 1
  • 8
  • 18

2 Answers2

4

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

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

If you are using PCRE, you could assert a digit on the left of the underscore and match a digit after. Then use make use of SKIP FAIL.

In the replacement use a dot:

(?<=\d)_\d(*SKIP)(*FAIL)|_
  • (?<=\d) Positive lookbehind, assert what is on the left is a digit
  • \d(*SKIP)(*FAIL) Consume the digit which should not be part of the match result
  • | Or
  • _ Match a single underscore

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70