-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathJavaRegexExpressions.java
More file actions
37 lines (26 loc) · 1.16 KB
/
JavaRegexExpressions.java
File metadata and controls
37 lines (26 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.zetcode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaRegexExpressions {
public static void main(String[] args) {
String[] expressions = {"16 + 11", "12 * 5", "27 / 3", "2 - 8"};
String pattern = "(\\d+)\\s+([-+*/])\\s+(\\d+)";
for (var expression : expressions) {
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(expression);
while (matcher.find()) {
int val1 = Integer.parseInt(matcher.group(1));
int val2 = Integer.parseInt(matcher.group(3));
String oper = matcher.group(2);
var result = switch (oper) {
case "+" -> String.format("%s = %d", expression, val1 + val2);
case "-" -> String.format("%s = %d", expression, val1 - val2);
case "*" -> String.format("%s = %d", expression, val1 * val2);
case "/" -> String.format("%s = %d", expression, val1 / val2);
default -> "Unknown operator";
};
System.out.println(result);
}
}
}
}