0

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.

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.