Reputation: 2618
I have a python regex that match method always return None. I tested in pythex site and the pattern seems OK.
But when I try with re module, the result is always None:
import re
a = re.match(re.compile("\.aspx\?.*cp="), 'page.aspx?cpm=549&cp=168')
What am I doing wrong?
Upvotes: 2
Views: 1826
Reputation: 1121494
re.match()
only matches at the start of a string. Use re.search()
instead:
re.search(r"\.aspx\?.*cp=", 'page.aspx?cpm=549&cp=168')
Demo:
>>> import re
>>> re.search(r"\.aspx\?.*cp=", 'page.aspx?cpm=549&cp=168')
<_sre.SRE_Match object at 0x105d7e440>
>>> re.search(r"\.aspx\?.*cp=", 'page.aspx?cpm=549&cp=168').group(0)
'.aspx?cpm=549&cp='
Note that any re
functions that take a pattern, accept a string and will call re.compile()
for you (which caches compilation results). You only need to use re.compile()
if you want to store the compiled expression for re-use, at which point you can call pattern.search()
on it:
pattern = re.compile(r"\.aspx\?.*cp=")
pattern.search('page.aspx?cpm=549&cp=168')
Upvotes: 9