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

2024-10-03 19:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 字符串代码restringmatchregexprintmatches
2条回答

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

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

如果需要匹配整个字符串,还应在开头包含“^”字符以匹配字符串的开头:

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

仅当整个字符串与该选择匹配时才匹配。你知道吗

python ^{}与C++ STD中的^ {CD2>}不一样::ReGEX或java ^ {CD3>}方法,它只在字符串的 Stest中搜索匹配。你知道吗

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance.

因此,要使与ptr2的匹配失败,如果使用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

相关问题 更多 >