简体   繁体   中英

Python - Regex find second match first

I have a little problem with Python regex.

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.

Can anyone plesase help me to esure that regex will find (1) f function first? Thanks.

BTW I cant understand why it find firstly the second function f function. Not the first, not the last, but the second. It's weird.

Use re.findall with following regex :

>>> 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 [^( ]*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM