首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >字符串使用python中的regex匹配模式。

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

Stack Overflow用户
提问于 2016-02-09 23:49:52
回答 2查看 58关注 0票数 1

怎么啦?

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2016-02-09 23:55:26

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

代码语言:javascript
运行
复制
str1=re.compile(r'[a-zA-Z0-9]+$')

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

代码语言:javascript
运行
复制
str1=re.compile(r'^[a-zA-Z0-9]+$')

只有当整个字符串与该选择匹配时,才会匹配。

票数 1
EN

Stack Overflow用户

发布于 2016-02-10 00:25:32

Python re.match与Java::regex或C++ String#matches方法中的regex_match不同,它只搜索字符串开头的匹配项。

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

因此,要与锚匹配失败,正则表达式应该只有一个 $锚(如果您使用的是** re.match,则在末尾应该有一个 \Z**)

请参阅IDEONE demo

代码语言:javascript
运行
复制
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@@@@')

如果计划使用,则需要 ^ 和锚点才能使用全字符串匹配

代码语言:javascript
运行
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35296283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档