Python在字符串中的特定点重新匹配

2024-03-28 10:39:53 发布

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

如果我在Python中有一个给定的字符串s,那么可以很容易地检查正则表达式是否匹配从字符串中特定位置i开始的字符串吗?你知道吗

我宁愿不把整个字符串从i切到最后,因为它看起来不太可伸缩(我认为排除了re.match)。你知道吗


Tags: 字符串rematch
2条回答

^{}不直接支持这一点。但是,如果使用^{}预编译正则表达式(通常是个好主意),那么^{}的类似方法^{}(和^{})都采用可选的pos参数:

The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the '^' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

示例:

import re
s = 'this is a test 4242 did you get it'
pat = re.compile('[a-zA-Z]+ ([0-9]+)')
print pat.match(s, 10).group(0)

输出:

'test 4242'

尽管re.match不支持这一点,但是新的^{}模块(旨在取代re模块)拥有大量新特性,包括posendpos参数,用于searchmatchsubsubn。尽管还不是官方的,^{}模块可以通过pip安装,并适用于Python版本2.5到3.4。举个例子:

>>> import regex

>>> regex.match(r'\d+', 'abc123def')

>>> regex.match(r'\d+', 'abc123def', pos=3)
<regex.Match object; span=(3, 6), match='123'>

>>> regex.match(r'\d+', 'abc123def', pos=3, endpos=5)
<regex.Match object; span=(3, 5), match='12'>

相关问题 更多 >