Search code examples
c#regexregex-lookaroundsregex-groupregex-greedy

RegEx for capturing a word in between = and ;


I want to select word2 from the following :

word2;word3

word2 that is between ; and start of the line unless there is a = in between. In that case, I want start from the = instead of the start of the line like word2 from

word1=word2;word3

I have tried using this regex

(?<=\=|^).*?(?=;)

which select the word2 from

word2;word3

but also the whole word1=word2 from

word1=word2;word3

Solution

  • You can use an optional group to check for a word followed by an equals sign and capture the value in the first capturing group:

    ^(?:\w+=)?(\w+);
    

    Explanation

    • ^ Start of string
    • (?:\w+=)? Optional non capturing group matching 1+ word chars followed by =
    • (\w+) Capture in the first capturing group 1+ word chars
    • ; Match ;

    See a regex demo

    In .NET you might also use:

    (?<=^(?:\w+=)?)\w+(?=;)
    

    Regex demo | C# demo

    enter image description here