swarajd
swarajd

Reputation: 1007

Match components of arithmetic expression with regex

I created a regular expression:

((\(\s*)          #match start parens
|(\d+\.?\d*)      #match a number
|([+-/%^!])       #match operators
|([*])            #match the asterisk operator
|(\s*\)))+        #match the end parens

that is supposed to separate parentheses, numbers (integers and decimal (3 and 6.28)), and operators (+-/*^%!). I have tried a few tests

( (2 3 +) 6.28 +)  
(3.14 6.28 +)
( (3 4 +) (5 6 +) *)

and I have noticed a few things. When I run the regular expression on expressions with two start parens, it seems to ignore one of the parentheses, and testing on the site seems to yield many instances of null and repetition of characters. Is there a way to match a valid expression and assign that to it's own group? For example, if I have the expression ( (2 3 +) 6.28 +), the groups generated would be: [(, (, 2, 3, +, 6.28, +, )]?

Upvotes: 0

Views: 1337

Answers (1)

Stephan
Stephan

Reputation: 43033

Try this:

Sample code

public static void main(String[] args) {
    String test ="((6.28 + 3.14) + 7.56)";
    String re = "\\(|\\)|\\d+\\.?\\d*|[+-/%^!*]";

    List<String> components = new ArrayList<String>();

    Pattern p = Pattern.compile(re);
    Matcher m = p.matcher(test);

    while(m.find()) {
        components.add(m.group());
    }

    System.out.println(components);
}

Output

[(, (, 6.28, +, 3.14, ), +, 7.56, )]

Upvotes: 1

Related Questions