我使用下面的代码来检查字符串是否与使用regex的模式匹配。因为ptr2
不应该与模式匹配,但是结果有匹配项。怎么了?你知道吗
ptr1="ptreee765885"
ptr2="hdjfhdjh@@@@"
str1=re.compile(r'[a-zA-Z0-9]+')
result=str1.match(ptr1)
result1=str1.match(ptr2)
if str1.match(ptr2):
print (" string matches %s",ptr2)
else:
print (" string not matches pattern %s",ptr2)
您需要添加$以匹配字符串的结尾:
如果需要匹配整个字符串,还应在开头包含“^”字符以匹配字符串的开头:
仅当整个字符串与该选择匹配时才匹配。你知道吗
python ^{} 与C++ STD中的^ {CD2>}不一样::ReGEX或java ^ {CD3>}方法,它只在字符串的 Stest中搜索匹配。你知道吗
因此,要使与
ptr2
的匹配失败,如果使用re.match
,则正则表达式应该只在末尾有一个$
(或\Z
)锚点:见IDEONE demo:
如果计划使用^{} ,则需要同时使用
^
和$
锚来要求完整字符串匹配:Another demo
相关问题 更多 >
编程相关推荐