检查字符串是否包含正则表达式的模式

时间:2014-02-25 12:56:07

标签: python

在我的python函数中,如果提供的参数包含表示正则表达式的字符串(ex - r'^\D{2}$'),我想采取一些操作。如何检查该字符串是否具有这样的正则表达式?

5 个答案:

答案 0 :(得分:3)

也许尝试编译字符串:

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

答案 1 :(得分:1)

您需要re模块。

import re

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

答案 2 :(得分:0)

试试这个,

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

答案 3 :(得分:0)

试试这个:

import re

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

# do something with your matched string

答案 4 :(得分:0)

有一个很棘手的方法。您可以尝试将模式与其自身作为字符串进行匹配,如果模式返回None,则可以将其视为regexp。

import re

def is_regex_pattern(pattern: str) -> bool:
    """Returns False if the pattern is normal string"""
    return not re.match(pattern, pattern)