python - 匹配两个字符之间的字符串

标签 python regex

前几天我回答了一个关于查找两个指定字符之间出现的字符串的问题。我最终得到了这个相当基本的正则表达式:

>>> import re
>>> def smallest_between_two(a, b, text):
...     return re.findall(re.escape(a) + "(.*?)" + re.escape(b), text)
...
>>> smallest_between_two(' ', '(', 'def test()')
['test']
>>> smallest_between_two('[', ']', '[this one][this one too]')
['this one', 'this one too']
>>> smallest_between_two('paste ', '/', '@paste "game_01/01"')
['"game_01']

但是,当我再次查看它时,我意识到当一场比赛部分包含在另一场比赛中时可能会出现一个常见错误。这是一个例子:

>>> smallest_between_two(' ', '(', 'here is an example()')
['is an example']

我不确定为什么它没有找到 an example ,和example ,因为这两者也发生在 ' ' 之间和一个 '('

我宁愿不这样做来查找其他匹配项:

>>> first_iteration = smallest_between_two(' ', '(', 'here is an example()')
>>> smallest_between_two(' ', '(', first_iteration[0] + '(')
['an example']

最佳答案

我会解释为什么你的会这样工作。重叠匹配请参见the answer already provided by cᴏʟᴅsᴘᴇᴇᴅ使用 regex 模块的 findall 方法和 overlapped=True 关键字参数。

<小时/>

您的匹配是这样的,因为正则表达式模式开头的空格与输入中的第一个空格匹配,然后非贪婪量词 .*? 匹配该空格与下一个 ( 之间的最小值。因此,它运行正常。为了更好地理解它,请使输入字符串 here is an example()another example()

现在,要在这种情况下获得最短匹配,您可以使用零和负向前查找来确保之间没有空格:

 (?!.* )(.*?)\(

所以:

In [81]: re.findall(r' (?!.* )(.*?)\(', 'here is an example()')
Out[81]: ['example']

关于python - 匹配两个字符之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48846867/

相关文章:

python - tkinter Entry 小部件中的可见文本变量

python - Python + Cairo + GTK/GDK 像素缓冲区的简单设置

python - 在 Python 桌面应用程序中的何处存储用户凭据?

php - preg_match 转储空数组

C# regex 删除不可打印字符和控制字符,在混合了多种不同语言、unicode 字母的文本中

python - 使用 Pandas 中的 apply 函数来使用每行的正则表达式计数

ios - 无法匹配整个正则表达式

python,如何在范围循环中跳过行

python - 从 dropbox API 构建目录树

java - 正则表达式在 Java 中替换掉 'section character'