正则表达式 - 匹配返回无.我哪里错了? [英] Regex - match returns None. Where am I wrong?

查看:43
本文介绍了正则表达式 - 匹配返回无.我哪里错了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>进口重新>>>s = '这是一个测试'>>>reg1 = re.compile('test$')>>>match1 = reg1.match(s)>>>打印匹配 1没有任何

在 Kiki 中匹配 s 末尾的测试.我想念什么?(我也试过 re.compile(r'test$'))

解决方案

使用

match1 = reg1.search(s)

相反.match 函数匹配字符串的开头……请参阅文档这里:

<块引用>

Python 提供了两种不同的基于正则表达式的原始操作:re.match() 只检查字符串开头的匹配,而 re.search()> 检查字符串中任何位置的匹配(这是 Perl 默认所做的).

>>> import re
>>> s = 'this is a test'
>>> reg1 = re.compile('test$')
>>> match1 = reg1.match(s)
>>> print match1
None

in Kiki that matches the test at the end of the s. What do I miss? (I tried re.compile(r'test$') as well)

解决方案

Use

match1 = reg1.search(s)

instead. The match function only matches at the start of the string ... see the documentation here:

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

这篇关于正则表达式 - 匹配返回无.我哪里错了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆