Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex: extract function names

I'm trying to extract a list of function names from a formula, but my regex is not working.

Given ( aaa(111) + bbb(222) ) / ccc ( 333 ) I need to obtain an array of strings containing aaa, bbb and ccc. Instead, I'm getting aaa(, bbb( and ccc (. how to make this work?

This is my attempt:

    String formula = "( aaa(111) + bbb(222) ) / ccc ( 333 )";
    Pattern pattern = Pattern.compile("((\\w+)\\s*\\()");
    Matcher matcher = pattern.matcher(formula);

    while(matcher.find()){
        System.out.println(matcher.group(1));
    }
like image 916
ps0604 Avatar asked Sep 13 '26 12:09

ps0604


1 Answers

You have 2 capturing groups in your pattern:

  • the external parentheses
  • the ones around \\w+

Since you are only interested in the second one, you should either

  • take the second group: matcher.group(2)
  • remove the external parentheses:

    Pattern pattern = Pattern.compile("(\\w+)\\s*\\(");
    

Notice that matcher.group(0) is always the match of the whole pattern (so equivalent to your external parentheses here)

like image 75
Didier L Avatar answered Sep 16 '26 01:09

Didier L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!