Home > Net >  Regex to find two strings within a pipe delimited string
Regex to find two strings within a pipe delimited string

Time:03-03

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.

CodePudding user response:

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

CodePudding user response:

If "apple" and "red" need to appear between the pipes, use:

^.*?apple[^|]*red.*?

Explanation: Force any characters between "apple" and "red" not to be a pipe symbol |. You can also get rid of the greedy match ?, then.

See for yourself at regex101...

  • Related