Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex between two characters – Matched between many same characters

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(?<=\|).+?(?=(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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading