Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python match regex always returning None

Tags:

python

regex

I have a python regex that match method always return None. I tested in pythex site and the pattern seems OK.

Pythex example

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?

like image 212
Leonardo Andrade Avatar asked Feb 10 '26 18:02

Leonardo Andrade


1 Answers

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')
like image 157
Martijn Pieters Avatar answered Feb 12 '26 09:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!