Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

|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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading