Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why python re module does not work with @? [duplicate]

Tags:

python

regex

In the following example shows weird problem: Python pattern does not work.

import re
data = r'blah blah @Component blah blah'
m = re.match(r'\@Component', data)
print m

It would print out:

None

What did I miss here?

like image 971
Artem Avatar asked Feb 14 '26 08:02

Artem


2 Answers

You need to use re.search instead, and @ has no special meaning so you do not need to escape it.

>>> re.search(r'@Component', data).group()
'@Component'
like image 153
hwnd Avatar answered Feb 15 '26 22:02

hwnd


match tries to match the pattern at the beginning of the string. Use search instead. Also, @ doesn't have any special meaning in Python's regex, so you don't need to escape it.

Working code:

>>> re.search('(@Component)', data).groups()
('@Component',)
like image 25
vaultah Avatar answered Feb 15 '26 21:02

vaultah



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!