In my python function I want to take some action if supplied parameter contains a string representing a regex (ex-r'^\D{2}$'). How can I check if that string has regex pattern like this?
-
2So, in other words, you have a string, and want to know if it can be used as a regex pattern?Kevin– Kevin2014-02-25 13:01:11 +00:00Commented Feb 25, 2014 at 13:01
Add a comment
|
5 Answers
Perhaps attempt to compile the string:
def is_regex(s):
try:
re.compile(s)
return True
except:
return False
3 Comments
gliese581g
it doesnt throw exception for something like this : re.compile('Hello World')
Dan D.
True, but that not an error as
re.compile('Hello World').match('Hello World').group(0) == 'Hello World'.Dan D.
If you don't want
'Hello World' to be considered valid, you would need to define what subset of regexes are to be accepted. As clearly that remark means that you don't want the entire set of regexes.There is a tricky way to do it. You can try to match the pattern with itself as a string and if it returns None you can consider it as regexp.
import re
def is_regex_pattern(pattern: str) -> bool:
"""Returns False if the pattern is normal string"""
return not re.match(pattern, pattern)
2 Comments
jtlz2
This is super neat - a hidden gem! Does it ever fail?
jtlz2
Except I think it should rather be:
return not re.match(pattern, pattern) is not None to work properly. Otherwise it always seems to return False. It also doesn't pay attention to whether there's an r prefix to the string.You need the re module.
import re
s = <some string>
p = <regex pattern>
if re.search(p, s):
# do something
4 Comments
gliese581g
thanks for the answer. But there could be too many regex patterns
gliese581g
in you code, I have to know it beforehand that which patterns I have to check the string against
Jayanth Koushik
you want to search for dynamic patterns?
gliese581g
no problem, I got to know about search method of re
Try this ,
import re
pattern=r'^\D{2}$'
string="Your String here"
import re
try:
re.compile(pattern)
is_valid = True
except re.error:
is_valid = False
if is_valid:
matchObj = re.search(pattern, string, flags=0)
if matchObj :
#do something
else:
#do something
2 Comments
Jayanth Koushik
The questions says "contains a string representing a regex". search should be used, not match.
Kevin
I think the OP is receiving the string
'^\D{2}$' from an outside source, and wants to determine if it can be used as a regex at all. Rather than return True for valid pattern strings and False otherwise, your code simply crashes for bad patterns.