如果我在 Python 中有一个给定的字符串 s
,是否可以轻松地检查正则表达式是否匹配从字符串中特定位置 i
开始的字符串?
我宁愿不将整个字符串从 i
切到末尾,因为它看起来不太可扩展(我认为排除了 re.match
)。
最佳答案
re.match
不直接支持这个。但是,如果您使用 re.compile
预编译您的正则表达式(通常是个好主意) , 然后是 RegexObject
类似的方法,match
(和 search
)都采用可选的 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'
关于Python在字符串中的特定点重新匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22444064/