Reputation: 729
Regex to check if .
in the string is followed by any of the other regex meta-characters -> ^ $ * + ? { } [ ] \ | ( )
How to do this?
I'm trying to do something like below:
foo.bar
-> dot is not followed by any other meta characters, so return false
foo.*bar
-> return true (because . is followed by *)
gmail.com
-> return false
bar.+gmail
-> return true
bar.
-> return false
I'm very new to regex. Tried to do something like below:
import re
pattern = re.compile(r"([.][\^$*+?{}\[\]\|()]+)+")
print bool(pattern.match("foo.*bar"))
But it's not correct plz help.
Upvotes: 0
Views: 57
Reputation: 15816
Your regexp is mostly correct but some characters are excessively escaped in the character class (for example, |
doesn't have to be escaped when used inside the class).
You need to use search
method instead of match
. There's a subtle difference between search
and match
: https://docs.python.org/3/library/re.html#re.match
In [1]: import re
In [2]: r = re.compile('\.[\^$*+?{}\[\]|()]')
In [4]: bool(r.search("foo.*bar"))
Out[4]: True
In [5]: bool(r.search("foo.bar"))
Out[5]: False
Also, it is better to start learning with Python 3 — version 2 is obsolete.
Upvotes: 1