Search code examples
.netregexdelimited

Regex to find two strings within a pipe delimited string


I need to find a match within the delimited string if the following two words appear between the pipes: apple and red

Example string 1 (should give a match):

|big blueberries blue|awesome lemon yellow|apple nice delicious red|

Example string 2 (should not give match):

|big blueberries apple|awesome lemon yellow|nice delicious red|

RegEx tried:

^.*?apple.*?red.*?

Which (kind of) works, but not sure how to include the pipe logic i.e. search between pipes.


Solution

  • If the 2 words in that order have to be between 2 pipes:

    ^[^|\r\n]*\|.*?\bapple\b[^|\r\n]*\bred\b[^|\r\n]*\|.*
    
    • ^ Start of string
    • [^|\r\n]*\| Match any char except | or a newline and then match |
    • .*? Match as least as possible
    • \bapple\b Match the word apple
    • [^|\r\n]* Match optional chars other than | or a newline
    • \bred\b Match the word red
    • [^|\r\n]*\| Match any char except | or a newline and then match |
    • .* Match the rest of the line

    .NET Regex demo

    If the order does not matter, you could use a capture group for either apple or red, and match the same word again, asserting that is using a negative lookhead and a backreference that it is not already matched:

    ^[^|\r\n]*\|.*?\b(apple|red)\b[^|\r\n]*\b(?!\1)(?:apple|red)\b[^|\r\n]*\|.*
    

    See another .NET regex demo