-2

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?

Dejell
  • 13,947
  • 40
  • 146
  • 229

1 Answers1

2
  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'  
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52