Dejell Dejell - 10 days ago 6
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")
print pattern.search(my_string)


It prints None. Why?

Answer
  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 re.search and re.match


Example

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

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

 >>> pattern.match(my_string)

 >>> pattern.search(my_string)
 <_sre.SRE_Match object at 0x10ca2fbf8>
 >>> match = pattern.search(my_string)
 >>> match.group()
 'App2 iPhone'