0

Given the following data

  1. "apple orange plum"
  2. "apple grape plum"

I will have a given term which will determine if something is a match.

e.g "apple orange plum pear cherry"

I need to write a regular expression which will match on [1.] but not [2.] because my term does not contain "grape"

I dont know if this is possible or not with regular expressions?

OnlineCop
  • 4,019
  • 23
  • 35
Matthew
  • 639
  • 5
  • 11

2 Answers2

1

Languages that support lookaheads (Javascript, PCRE, Ruby, Java, Python) can use them to test whether the line/string contains these values, in any order:

^(?=.*\b(item1)\b)(?=.*\b(item2)\b)(?=.*\b(item3)\b)

For your [1.] data, this becomes:

^(?=.*\b(apple)\b)(?=.*\b(orange)\b)(?=.*\b(plum)\b)

You can see this on regex101 here.

For your [2.] data, this becomes:

^(?=.*\b(apple)\b)(?=.*\b(grape)\b)(?=.*\b(plum)\b)

You can see this on regex101 here.

You, of course, don't need to have the capture groups INSIDE of the lookaheads. You could simply match those items (without capture groups) and then use .* at the end of the pattern to match from the start of the line to the end:

^(?=.*\bapple\b)(?=.*\borange\b)(?=.*\bplum\b).*

Notice on regex101 however that you no longer see results under MATCH INFORMATION (nothing was captured), but the entire line WAS selected as the match was valid.

OnlineCop
  • 4,019
  • 23
  • 35
1

you can use

^(((apple|orange|plum|pear|chery)(?: |$))+)$

DEMO regex101

Explanation

(apple|orange|plum|pear|chery) any of these words

(?: |$) non capturing group

Community
  • 1
  • 1
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62