[英]Python - Regex find second match first
I have a little problem with Python regex. 我对Python正则表达式有一点问题。
I need to find name of the function in this string: (the (number) arent in the string in my file) 我需要在这个字符串中找到函数的名称:(我的文件中的字符串中的(数字)不是)
(1)void f(int test);
(2)void h(int test);
(3)double f(int test1, int test2, ...);
(4)double f(int test1, int test2);
I have this code: 我有这个代码:
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)
when I print the functionName, it prints firstly the (3) f function, when I need firstly to write (1) f function. 当我打印functionName时,它首先打印(3) f函数,当我首先需要写(1) f函数时。
Can anyone plesase help me to esure that regex will find (1) f function first? 任何人都可以帮助我确保正则表达式会首先找到(1) f函数吗? Thanks.
谢谢。
BTW I cant understand why it find firstly the second function f function. 顺便说一句我不明白为什么它首先找到第二个函数f函数。 Not the first, not the last, but the second.
不是第一个,不是最后一个,而是第二个。 It's weird.
有点奇怪。
Use re.findall
with following regex : 使用
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')]
The regex r'(\\(\\d\\))[^( ]*(.*)\\('
is contain 2 capture grouping first is (\\(\\d\\))
that will match a digit within a parenthesis and second is (.*)
that will match any thing before (
and after [^( ]*
正则表达式
r'(\\(\\d\\))[^( ]*(.*)\\('
首先包含2个捕获分组是(\\(\\d\\))
,它将匹配括号内的数字,第二个是(.*)
将匹配任何事物之前(
和[^( ]*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.