Dejell Dejell - 1 month ago 9
Python Question

Python regex if all whole words in string

I have the following a string, I need to check if

  • the string contains App2 and iPhone,

  • but not App and iPhone

I wrote the following:

campaign_keywords = "App2 iPhone"
my_string = "[Love]App2 iPhone Argentina"
pattern = re.compile("r'\b" + campaign_keywords + "\b")

It prints None. Why?

  1. The raw string notation is wrong, the r should not be inside the the quotes. and the second \b should also be a raw string.
  2. The match function tries to match at the start of the string. You need to use search or findall

    Difference between and re.match


 >>> pattern = re.compile(r"\b" + campaign_keywords + r"\b")

 >>> pattern.findall(my_string)
 ['App2 iPhone']

 >>> pattern.match(my_string)

 <_sre.SRE_Match object at 0x10ca2fbf8>
 >>> match =
 'App2 iPhone'