3

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?

1
  • 2
    So, in other words, you have a string, and want to know if it can be used as a regex pattern? Commented Feb 25, 2014 at 13:01

5 Answers 5

4

Perhaps attempt to compile the string:

def is_regex(s):
    try:
       re.compile(s)
       return True
    except:
       return False
Sign up to request clarification or add additional context in comments.

3 Comments

it doesnt throw exception for something like this : re.compile('Hello World')
True, but that not an error as re.compile('Hello World').match('Hello World').group(0) == 'Hello World'.
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.
2

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

This is super neat - a hidden gem! Does it ever fail?
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.
1

You need the re module.

import re

s = <some string>
p = <regex pattern>
if re.search(p, s):
    # do something

4 Comments

thanks for the answer. But there could be too many regex patterns
in you code, I have to know it beforehand that which patterns I have to check the string against
you want to search for dynamic patterns?
no problem, I got to know about search method of re
0

try this:

import re

match_regex = re.search(r'^\D{2}$','somestring').group()

# do something with your matched string

Comments

0

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

The questions says "contains a string representing a regex". search should be used, not match.
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.

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.