Home > Software engineering >  Regex between two characters - Matched between many same characters
Regex between two characters - Matched between many same characters

Time:12-02

I have a string

[ 14.21 | | Pobiedziska Letnisko 2 11.16 | 1 ]

I need a value between second "|" character and number "2" or "1" enter image description here Only this part of string without the "|" character and without the number. I was trying this pattern

(?<=\|). ?(?=(1|2))

But as you can see, this pattern is not good as the match started with the first character "|" and I need to do it from the second "|" character.

CodePudding user response:

You could use a capture group starting after the second pipe char matching till the first occurrence of 1 or 2.

Note that . ? can also match | so it will cross the | if the 1 or 2 is after a pipe char at the right.

^[^|]*\|[^|]*\|(. ?)\b[21]\b

Regex demo

If you don't want to cross newlines or pipe chars, you can extend the negated character class like ^[^|\r\n]*

Another option using lookarounds as in your question with a negated character class not crossing a pipe char:

(?<=^[^|]*\|[^|]*\|)[^|] (?=\b[21]\b)
  • (?<=^[^|]*\|[^|]*\|) Assert 2 pipe chars to the left of the current position
  • [^|] Match any character except |
  • (?=\b[21]\b) Postive lookahead, assert 2 or 1 to the right

.NET Regex demo

  • Related