0

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.

apples-oranges
  • 959
  • 2
  • 9
  • 21

2 Answers2

1

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

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Could you please give an example if order does not matter (between the 2 pipes). Thank you! – apples-oranges Mar 03 '22 at 12:12
  • 1
    @apples-oranges If the order does not matter, you could for example use `^[^|\n]*\|.*?\b(apple|red)\b[^|\n]*\b(?!\1)(?:apple|red)\b[^|\n]*\|.*` https://regex101.com/r/7UeNnW/1 – The fourth bird Mar 03 '22 at 12:17
  • Sorry for the late reply -- what if I want to match only one word in between the pipes. I assume this will work?: `^[^|\r\n]*\|.*?\bapple\b[^|\r\n]*` Thanks again! – apples-oranges Mar 07 '22 at 13:39
  • 1
    @apples-oranges That is correct, if you want to be sure that there is an ending pipe you can also extend it to `^[^|\r\n]*\|.*?\bapple\b[^|\r\n]*\|` – The fourth bird Mar 07 '22 at 14:15
0

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...

zb226
  • 9,586
  • 6
  • 49
  • 79