0

I have a math expression stored as a String:

String math = "12+3=15";

I want to separate the string into the following:

  • int num1 (The first number, 12)
  • int num2 (The second number, 3)
  • String operator (+)
  • int answer (The answer, 15)

(num1 and num2 can be digits between 0-20, and operator can be either +,-,*,/)

What is the easiest way to achieve this? I was thinking about regular expressions, but I'm not sure how to do it.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
user2939293
  • 793
  • 5
  • 16
  • 41

2 Answers2

1

Now, don't scowl at me.. You asked for the simplest solution :P

public static void main(String[] args) {
    String math = "12+3=15";
    Pattern p = Pattern.compile("(\\d+)(.)(\\d+)=(\\d+)");
    Matcher m = p.matcher(math);
    while (m.find()) {
        System.out.println(m.group(1));
        System.out.println(m.group(2));
        System.out.println(m.group(3));
        System.out.println(m.group(4));
    }
}

O/P :

12
+
3
15

EDIT : (\\d+)(.)(\\d+)=(\\d+) --> 
 \\d+ matches one or more digits.
 . matches anything
 () --> captures whatever is inside it
(\\d+)(.)(\\d+)=(\\d+) --> captures one or more digits followed by anything (+-* etc) then again one or more digits and ignores the "=" and then captures digits again.

captured groups are named from 1 to n.. group 0 represents the entire string.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Seems like a nice solution. I will try it. Can you please explain the line Pattern p = Pattern.compile("(\\d+)(.)(\\d+)=(\\d+)"); I want to learn what I am doing and why. Thank you – user2939293 Feb 27 '15 at 11:54
  • @vks yes it seem like an easier way. But operator can be either +,-,*,/ – user2939293 Feb 27 '15 at 11:57
  • @user2939293 - edited my answer and explained it :P – TheLostMind Feb 27 '15 at 11:58
  • Too bad, that you answer also accepts invalid strings like `"123=15"`. – Tom Feb 27 '15 at 12:01
  • @Tom - The OP said - *Yes, this is the only format I have* :P .. I could change it to `[+\\-*/]` .. But it won't make much of a difference. :) – TheLostMind Feb 27 '15 at 12:02
  • @TheLostMind Well then let's hope he won't expand his program or read these equations from untrusted^ sources :P. (^ but your code won't cause any harm anyway :D) – Tom Feb 27 '15 at 12:07
  • @Tom - Or lets just hope that he *expands* his program to support `% ^ | &` etc :P – TheLostMind Feb 27 '15 at 12:09
0
\\b(\\d+)\\b|([+*\/-])

You can simply do this and grab the capture.See demo.

https://regex101.com/r/wU7sQ0/30

Or simply split by \\b.See demo.

https://regex101.com/r/wU7sQ0/31

var re = /\b(\d+)\b|([+=\\-])/gm;
var str = '12+3=15';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
vks
  • 67,027
  • 10
  • 91
  • 124