怎么啦?
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)发布于 2016-02-09 23:55:26
您需要添加$以匹配字符串的末尾:
str1=re.compile(r'[a-zA-Z0-9]+$')如果需要匹配整个字符串,还应在开头包含^字符以匹配字符串的开头:
str1=re.compile(r'^[a-zA-Z0-9]+$')只有当整个字符串与该选择匹配时,才会匹配。
发布于 2016-02-10 00:25:32
Python re.match与Java::regex或C++ String#matches方法中的regex_match不同,它只搜索字符串开头的匹配项。
如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的
MatchObject实例。
因此,要与锚匹配失败,正则表达式应该只有一个 $锚(如果您使用的是** re.match,则在末尾应该有一个 \Z**)
请参阅IDEONE demo
import re
ptr2="hdjfhdjh@@@@"
str1=re.compile(r'[a-zA-Z0-9]+$')
if str1.match(ptr2):
print (" string matches %s",ptr2)
else:
print (" string not matches pattern %s",ptr2)
# => (' string not matches pattern %s', 'hdjfhdjh@@@@')如果计划使用,则需要 ^ 和锚点才能使用全字符串匹配
import re
ptr2="hdjfhdjh@@@@"
str1=re.compile(r'^[a-zA-Z0-9]+$')
if str1.search(ptr2):
print (" string matches %s",ptr2)
else:
print (" string not matches pattern %s",ptr2)Another demo
https://stackoverflow.com/questions/35296283
复制相似问题