Georgie
Georgie

Reputation: 118

Replace comma decimal separator with regex without change it in text values

In txt file for example, with Notepad++ for example, I would target and replace the comma when it is used as a decimal separator in numbers surrounded by tabs ; and let it as a comma when it is used in some text.

I found a regex very nice: (?<=\t\d)*,(?=\d*\t)

It seems perfectly worked, but not: it does not work where the number ends the field.

See my example below. The regex also targets the first numbers in line 3 and 5.

enter image description here

But I would it only targets the number fully surrounded by tabs.

Please have you and idea?

Upvotes: 0

Views: 1405

Answers (1)

The fourth bird
The fourth bird

Reputation: 163237

The lookbehind is optional so it will also match the comma in ,

Notepad uses Boost regex engine, which does not support a quantifier in the lookbehind assertion, so (?<=\t\d+) will not work.

Instead, you could match the text and use an alternation to assert either a tab or the start / end of the string fi there can also be single numbers in the line.

(?:\t|^)\d+\K,(?=\d+(?:\t|$))

The pattern in parts:

  • (?:\t|^) Match either a tab or assert the start of the string
  • \d+ Match 1+ digits
  • \K, Forget what is matched so far and match a comma
  • (?=\d+(?:\t|$)) Positive lookahead, assert 1+ digits followed by either a tab or the end of the string to the right

See a regex demo.

enter image description here

If there should be mandatory tabs on the left and the right, you can omit the alternations and use the pattern posted by @JvdV in the comments.

Upvotes: 2

Related Questions