首页 文章

Python正则表达式匹配基于特定模式[暂停]

提问于
浏览
0

匹配字符串,如果只找到特定模式,则应拒绝其他整个字符串 .

例如,这里是字符串,它应匹配字符串,如果只有az,AZ,0-9,:(冒号), . (点),;(分号), - (连字符),“(双反转),(, )逗号,[]方括号,()括号,\(反斜杠)出现在该字符串中并且必须接受该字符串,如下所示它必须接受string1

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 回答

  • 1

    这是使用 re.sub 的一种方法

    Ex:

    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))
    

    Output:

    True
    False
    
  • 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))
    

    Output:

    True
    False
    

相关问题