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

标签 python regex

如果我在 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/

相关文章:

regex - 用于重新排序字段中字符串的正则表达式

Java正则表达式递归匹配

python - 如何从 Python 中的 TCP 套接字读取完整的 IP 帧?

python - ctypes找不到find dll函数

python - 如何使用 python 在 Mac OS X 中获取环境变量?

javascript - 正则表达式以及将字符串转换为数组以及来回 Javascript

MySql - 正则表达式提取数字的可变序列

python - 如何在 sklearn 中编码分类特征?

python - 使用 Python Mock 修补 API

regex - 第n个元素