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));
}
You have 2 capturing groups in your pattern:
\\w+Since you are only interested in the second one, you should either
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With