Only replace the pattern if the entire string matches the regular expression

I am sure that there is a trivial solution to this question, but I can’t understand that this is correct:
I want to replace a specific pattern in a string only if the entire string matches the regular expression.

So, in my case, the three pipes |should be replaced with underscores _only if the whole line is numbers and pipes:

|||10|||-80|||-120|||400           ---> replace
|||10|||asdf|||-120|||400          ---> don't replace
|||10|||-80|||400                  ---> replace
|||10|||-80|||-120|||400|||test    ---> don't replace

Expected Result:

___10___-80___-120___400
|||10|||asdf|||-120|||400
___10___-80___400
|||10|||-80|||-120|||400|||test

My attempts:

\|\|\|(?=\-?\d+)

replaces pipes if they are followed by numbers as expected, but, of course, also in "invalid" lines

^(\|\|\|\-?\d+){1,}$

matches the entire line and therefore I can not replace only pipes

, , , , , , .

+4
1

, ,

(?<=^(?:\|{3}-?\d+)*)\|{3}(?=-?\d+(?:\|{3}-?\d+)*$)

, :

(?m)(?<=^(?:\|{3}-?\d+)*)\|{3}(?=-?\d+(?:\|{3}-?\d+)*\r?$)

regex.

enter image description here

  • (?<=^(?:\|{3}-?\d+)*) - lookbehind, , :
    • ^ -
    • (?:\|{3}-?\d+)* - 3 |, - (-?), 1
  • \|{3} - 3
  • (?=-?\d+(?:\|{3}-?\d+)*$) - , ,
    • -?\d+ - -, 1 +
    • (?:\|{3}-?\d+)* - 0 3 | + -, 1 +
    • $ - .

#:

var res = Regex.Replace(s, @"(?<=^(?:\|{3}-?\d+)*)\|{3}(?=-?\d+(?:\|{3}-?\d+)*$)", "___", RegexOptions.ECMAScript);

RegexOptions.ECMAScript , \d ASCII.

+5

Source: https://habr.com/ru/post/1680286/


All Articles