字符串与python中使用regex的模式匹配

字符串与python中使用regex的模式匹配,python,regex,Python,Regex,我使用下面的代码检查字符串是否与使用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 ("

我使用下面的代码检查字符串是否与使用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)

您需要添加$以匹配字符串的结尾:

str1=re.compile(r'[a-zA-Z0-9]+$')
如果需要匹配整个字符串,还应在开头包含“^”字符以匹配字符串的开头:

str1=re.compile(r'^[a-zA-Z0-9]+$')

只有整个字符串匹配该选项。<> p> python与C++ STD中的ReXeXMatal/<代码>不一样::ReGEX或java <代码>字符串>匹配方法,它只在字符串的开始处搜索匹配。

如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的
MatchObject
实例

因此,如果要使与
ptr2
的匹配失败,正则表达式应该只有
$
(或
\Z
)锚,如果您使用
re.match

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

如果计划使用,则需要
^
$
锚定以要求完整的字符串匹配

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)

两个字符串都会匹配。您的目标是什么?两个字符串都有字母数字序列,这就是您测试的全部内容。您是否尝试过使用调试函数?如何检查字符串中是否有“-”、“whitspace”和“whitspace”|