python3中的Regex和verbose

2024-05-08 19:03:27 发布

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

我在读Dive into Python 3关于正则表达式,特别是使用重复冗长. 我试图搜索一个字符串,但它总是返回“None”。例如:

import re
pattern = '''
testing
'''

print(re.search(pattern, 'test', re.VERBOSE))

我原以为这应该返回除None之外的其他值,因为“testing”中存在字符“test”的模式。我也曾想,如果是这样的话:

^{pr2}$

如果我搜索同一个字符串,那么返回值None是有意义的。然而,不管怎样,我似乎总是得到一个返回值None。我做错什么了?在


Tags: 字符串testimportrenoneverbosesearch字符
1条回答
网友
1楼 · 发布于 2024-05-08 19:03:27

你有你的模式和文本搜索混淆。在

您要在文本test中查找testing,后者不够长。:-)

如果将两个(模式test,文本testing)颠倒过来:

>>> import re
>>> pattern = '''
... test
... '''
>>> print(re.search(pattern, 'testing', re.VERBOSE))
<_sre.SRE_Match object at 0x1062f4c60>

相关问题 更多 >