5

我有一个关于正则表达式的问题。使用or构造时

$ python
Python 2.7.3 (default, Sep 26 2012, 21:51:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> for mo in re.finditer('a|ab', 'ab'):
...     print mo.start(0), mo.end(0)
... 
0 1

我们只得到一个匹配,它被认为是最左边的第一个分支,被接受。我的问题是这是否可能以及如何构造一个正则表达式,它将产生(0,1)和(0,2)。而且,通常如何对 form 中的任何正则表达式执行此操作r1 | r2 | ... | rn

*同样,对于、+?构造,是否有可能实现这一点?默认情况下:

>>> for mo in re.finditer('a*', 'aaa'):
...     print mo.start(0), mo.end(0)
... 
0 3
3 3
>>> for mo in re.finditer('a+', 'aaa'):
...     print mo.start(0), mo.end(0)
... 
0 3
>>> for mo in re.finditer('a?', 'aaa'):
...     print mo.start(0), mo.end(0)
... 
0 1
1 2
2 3
3 3

第二个问题是,为什么空字符串在末尾匹配,但在其他任何地方都不匹配*and ?

编辑:

我想我现在意识到这两个问题都是无稽之谈:正如@mgilson 所说, re.finditer 只返回不重叠的匹配项,我猜每当正则表达式接受(a 的一部分)字符串时,它都会终止搜索。因此,使用 Python 匹配引擎的默认设置是不可能的。

虽然我想知道如果Python在正则表达式匹配中使用回溯,那么在接受字符串后让它继续搜索应该不是很困难。但这会破坏正则表达式的通常行为。

编辑2:

这在 Perl 中是可能的。请参阅下面@Qtax 的回答。

4

2 回答 2

1

Just want to mention that you can do such things in Perl, using an expression like:

(?:a|ab)(?{ say $& })(?!)

The (?{ code }) construct executes the code every time the regex engine gets to that position in the pattern. Here right after your regex, and it prints the content of the match so far. The (?!) after that fails the match, making the regex engine backtrack, and giving us the next possible match, and so on.

This will work for any kind of expression.

Example:

perl -E "$_='ab'; /(?:a|ab)(?{ say $& })(?!)/"

Output:

a
ab

Another example:

perl -E "$_='aaaa'; /a+(?{ say $& })(?!)/"

Output:

aaaa
aaa
aa
a
aaa
aa
a
aa
a
a
于 2013-02-07T03:16:00.867 回答
1

我不认为这是可能的。状态的文档re.finditer

返回一个迭代器,该迭代器在字符串中 RE 模式的所有非重叠匹配中产生 MatchObject 实例

重点是我的


在回答您关于为什么空字符串在其他地方不匹配的另一个问题时,我认为这是因为字符串的其余部分已经在其他地方匹配,并且finditer只为匹配的非重叠模式提供匹配(参见第一部分的答案;- )。

于 2013-02-07T02:13:58.593 回答