【问题标题】:Python - Regex find second match firstPython - 正则表达式首先找到第二个匹配项
【发布时间】:2015-06-26 09:57:28
【问题描述】:

我对 Python 正则表达式有点问题。

我需要在这个字符串中找到函数的名称:(我文件中的字符串中的(数字)不是)

(1)void f(int test);
(2)void h(int test);
(3)double f(int test1, int test2, ...);
(4)double f(int test1, int test2);

我有这个代码:

namePattern = "^[\s\S]*?\s?[*\s]*([a-zA-Z_][a-zA-Z_0-9]*)\s*\([\S\s]*?\).*?$"
functionName = re.sub(re.compile(namePattern, re.MULTILINE), r'\1', funcString)

当我打印functionName时,它首先打印(3)f函数,当我需要首先编写(1)f函数时。

谁能帮我确保正则表达式会首先找到 (1) f 函数?谢谢。

顺便说一句,我不明白为什么它首先找到第二个函数 f 函数。不是第一个,不是最后一个,而是第二个。这很奇怪。

【问题讨论】:

  • 似乎无法重现该问题:regex101.com/r/oI6aU6/1。右边的匹配信息显示所有函数确实在匹配中
  • 在 regex101 我有相同的输出。尽管在 Python 中是我发布的方式:/
  • 能否复制粘贴输出的单词,以便我们更好地理解它
  • 它在 Python 解释器中也能完美运行

标签: python regex


【解决方案1】:

re.findall 与以下正则表达式一起使用:

>>> s="""(1)void f(int test);
... (2)void h(int test);
... (3)double f(int test1, int test2, ...);
... (4)double f(int test1, int test2);"""

>>> re.findall(r'(\(\d\))[^( ]*(.*)\(',s)
[('(1)', ' f'), ('(2)', ' h'), ('(3)', ' f'), ('(4)', ' f')]

正则表达式r'(\(\d\))[^( ]*(.*)\(' 包含2 个捕获分组,第一个是(\(\d\)),它将匹配括号内的一个数字,第二个是(.*),它将匹配( 之前和[^( ]* 之后的任何内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多