Regular expression to find first match of string between characters

Viewed 70

Here's the text I have:

Dddd, Cccccccc - abcdefgh|abcdefgh|m$P,o29L|SomeOtherText
|abcdefgh||mmmin||
Aaaa, Bbbbbbbb - y123xxyz|y123xxyz|m$P,o29L|SomeOtherText
|y123xxyz||mmmax||

I'd like to have returned abcdefgh and y123xxyz after the first | and before second |, and only from lines starting with word character. What will the regex expression look like ?

So far I have this expression:

(?<=\|)(\w+)(?=\|)

which return all the occurrences of word between pipe characters, on all lines, but I'd like to have only matches from lines starting with word character (\w) - lines 1 and 3. How can I add this condition to my expression ?

1 Answers

You can use

(?<=^\w[^|]*\|)\w+(?=\|)

See the .NET regex demo

Details

  • (?<=^\w[^|]*\|) - a positive lookbehind that matches a location that is immediately preceded with
    • ^ - start of string
    • \w - a word char
    • [^|]* - zero or more chars other than a pipe char
    • \| - a pipe char
  • \w+ - one or more word chars
  • (?=\|) - a positive lookahead that requires a | char immediately to the right of the current location.
Related