Search code examples
python-3.xpython-re

regex match and extract the word before parenthesis


I have a line of strings in a file that i need to iterate over. Each line is of the form:

returnType ClassType functionName(int param1, double param2)
returnType ClassType functionName();

I want to iterate over each line and grab just the function name functionName via regex.

I have a solution without regex:

line.split("(")[0].split(" ")[-1]

which returns functionName

I would like to get a solution with regex if thats possible. Thanks This is what i have tried:

import re
pattern = re.compile(r"\w+^\(")

where I'm saying, match any character that contains a parenthesis and give me that item. But its returning empty for me thanks


Solution

  • A really basic starting point would be:

    \s(\w+)\(
    

    This captures one of more characters in the set [a-zA-Z0-9_] that are preceded by a space and followed by an open parenthesis.

    You may need to tweak based on the grammar of the language you're trying to match.