TimeIsNear TimeIsNear - 7 months ago 45
Java Question

Regular expression java how to addition 2 value?

how can I parse and addition two value?
Im usin this pattern:

String s = "6 + 7 =";

Included spacing, I need to get "13"

It is possible with regex, or there are an other way to do this easely?

Thanks in advance for ur help.


If you want to use regex you can do it this way:

Pattern pattern = Pattern.compile("(\\d+)\\s*\\+\\s*(\\d+)\\s*=");
Matcher matcher = pattern.matcher("6 + 7 =");
if (matcher.matches()) {
    System.out.println(Integer.valueOf(matcher.group(1)) + Integer.valueOf(matcher.group(2)));