Home > Software engineering >  Regex: match the function name without the parameter list, and with the template definition
Regex: match the function name without the parameter list, and with the template definition

Time:02-24

that sounded like an easy one (and it probably is) but I'm struggling with the following regex challenge.

I'm trying to identify the function name of all the following lines without including the parameter list (so trimming anything between parenthesis). UNLESS if it's part of a template description, that is between '<' and '>'. Additionally any artefacts after the method name should be ignored...

So far my best try was

^[^\(\)] 

For instance, here is a typical input covering all my cases:

operator()(Name::UI::IKeyListener*) const
notify<void (Name::UI::IMouseListener::*)(Name::UI::MouseEvent const&)>
forEachLoadCommand(Diagnostics&, void 
entry(void*)   144

Output:

operator
notify<void (Name::UI::IMouseListener::*)(Name::UI::MouseEvent const&)>
forEachLoadCommand
entry

I can't get the second line right, it will return "notify<void " which makes sense... but I do not know how to solve this.

I thought maybe an alternative group would help?

I've got a Regex101 sandbox already available here: https://regex101.com/r/JZvC15/1

Thanks!

CodePudding user response:

You may use this regex with an optional match for template substring i.e. <...>:

^\s*\w (?:<.*>)?

RegEx Demo

RegEx Details:

  • ^: Start
  • \s*: Match 0 or more whitespaces
  • \w : Match 1 word characters
  • (?:<.*>)?: An optional non-capturing group that matches longest <...> substring
  • Related