0

How do I construct a regex to see if any of the multiple words provided are contained in a string in python?

I've tried the below, but it matches words that contain the string. I only want to match whole words.

re.match("(one|two|three)", search_string, re.IGNORECASE)

With the above, words like clone would provide a match. However, I would like an exact match (e.g. one).

John Smith
  • 843
  • 2
  • 9
  • 21
  • With multiple lookaheads and word boundaries. – Jan Sep 19 '16 at 21:09
  • 1
    `re.search(r"\b(one|two|three)\b", search_string, re.IGNORECASE)` – Wiktor Stribiżew Sep 19 '16 at 21:10
  • @Wiktor: I guess, he rather wanted **multiple words** to be present in the string. – Jan Sep 19 '16 at 21:11
  • @Jan: *I only want to match whole words.* If a whole *string* is meant - [*Checking whole string with a regex*](http://stackoverflow.com/questions/3994493/checking-whole-string-with-a-regex) – Wiktor Stribiżew Sep 19 '16 at 21:11
  • Is [**`^(?=.*\bone\b)(?=.*\btwo\b).+$`**](https://regex101.com/r/gB2rN9/1) what you're looking for? – Jan Sep 19 '16 at 21:14
  • @WiktorStribiżew thank you. I tried multiple permutations and needed the `"r"`among other things. – John Smith Sep 19 '16 at 21:17
  • Aha, that means that the real duplicate is [*Does Python re module support word boundaries (\b)?*](http://stackoverflow.com/questions/3995034/does-python-re-module-support-word-boundaries-b) – Wiktor Stribiżew Sep 19 '16 at 21:22

0 Answers0