'Parse log level with a regular expression in C# [closed]

I have text that I want to parse. The log level for example:

This is simple [fail] text

So in this case I want to take [fail], so I do it with \[.*?\].

Now in case my log level is with this format: |fail| I want to be able to parse it as well, so I try to add this:

\[.*?\]|.*?\|

But in case my text is This is simple |fail| text, the match is only fail|.



Solution 1:[1]

You can use

(?:(\[)|(\|)).*?(?(1)]|\|)

See the regex demo. Or, only matching fail:

(?<=(?:(\[)|(\|))).*?(?=(?(1)]|\|))

See this regex demo.

Regex details

  • (?:(\[)|(\|)) - either [ (captured into Group 1) or | (captured into Group 2)
  • .*? - any zero or more characters other than line break chars, as few as possible
  • (?(1)]|\|) - a conditional construct: if Group 1 was matched ([), then match ], else, match |.

In the second pattern, the left- and right-hand boundaries are enclosed into non-consuming lookarounds.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen