基于特定模式的Python正则表达式匹配

时间:2018-12-10 05:33:39

标签: python regex

匹配字符串,如果仅找到特定模式,则应拒绝整个字符串。

例如,这里是字符串,如果只有az,AZ,0-9,:(冒号),。(点),;(分号),-(连字符),“(双反) ,(,)逗号,[]方括号,()括号,\(反斜杠)出现在该字符串中,并且必须接受该字符串,就像下面给出的那样,它必须接受字符串1

string1 = "This is nandakishor's messAGe'\; [to]test(897185) "few(1 -\ 2)" regexs"

如果字符串中包含$,%,^,&,@,#之类的其他内容,则必须拒绝整个字符串。像下面给出的那样,它必须拒绝string2

string2 = "This is nandakishor's messAGe'\; [to]test(89718$#!&*^!5) "few(1 -\ 2)" regexs"

2 个答案:

答案 0 :(得分:1)

这是使用re.sub

的一种方法

例如:

import re

string1 = '''This is nandakishor's messAGe'\; [to]test(897185) "few(1 -\ 2)" regexs'''
string2 = '''This is nandakishor's messAGe'\; [to]test(89718$#!&*^!5) "few(1 -\ 2)" regexs'''

def validateString(strVal):
    return re.sub(r"[^a-zA-Z0-9:;\.,\-\",\[\]\(\)\\\s*\']", "", strVal) == strVal

print(validateString(string1))
print(validateString(string2))

输出:

True
False

答案 1 :(得分:1)

另一种方式:

import re

string1 = '''This is nandakishor's messAGe'\; [to]test(897185) "few(1 -\ 2)" regexs'''
string2 = '''This is nandakishor's messAGe'\; [to]test(89718$#!&*^!5) "few(1 -\ 2)" regexs'''

def validate_string(str_to_validate):
    match_pattern1 = r'[a-zA-Z,():\[\];.\']'
    match_pattern2 = '[$%^&@#]'

    return re.search(match_pattern1, str_to_validate) and not re.search(match_pattern2, str_to_validate)

print(validate_string(string1))
print(validate_string(string2))

输出:

True
False