2 回答
TA贡献1803条经验 获得超6个赞
这是使用的一种方法 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
TA贡献1828条经验 获得超3个赞
其它的办法:
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
添加回答
举报