我正在寻找一种方法来返回字符串中给定正则表达式的第一个匹配项。看起来像 re.search
正是我正在寻找的方法。
但是,文档并未明确说明是否保证从搜索方法返回第一个匹配项。
文档声称该方法“扫描整个字符串”,这表明它从字符串的开头开始扫描。
但是我需要一些强有力的论据。仅仅测试在 cat1cat2
中找到 cat1
是不够的。
最好是官方文档或实现的提示。
最佳答案
我不想通读 re.search
的代码,因为它太多了。但是,如果我们查看 re.sub
的代码,我们看到它使用 re.search
,并且 re.sub
保证替换最左边出现的模式。因此,re.search
必须返回它。
相关代码来自_sre.c
(注释替换冗长的无关代码)
static PyObject*
pattern_subx(PatternObject* self, PyObject* ptemplate, PyObject* string,
Py_ssize_t count, Py_ssize_t subn)
{
// init stuff...
while (!count || n < count) {
state_reset(&state);
state.ptr = state.start;
status = sre_search(&state, PatternObject_GetCode(self));
// Do the replacement...
编辑:
感谢@Veedrac打开 issue , documentation已澄清声明
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object.
关于python - 正则表达式搜索是否保证返回第一个匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23906400/