简体   繁体   中英

Check if string contains pattern for regular expression

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?

Perhaps attempt to compile the string:

def is_regex(s):
    try:
       re.compile(s)
       return True
    except:
       return False

You need the re module.

import re

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

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

try this:

import re

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

# do something with your matched string

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM