Empty strings are allowed by \\d*
since it means zero or more digits. If you don't want to find strings that have zero digits (are empty) change \\d*
to \\d+
.
Demo
String s = "2+30*4+(5+6)*7";
Pattern p = Pattern.compile("\\d+|[()+*-]");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.print("Start index: " + m.start());
System.out.print(" End index: " + m.end() + " ");
System.out.println("-----> " + m.group());
}
Output:
Start index: 0 End index: 1 -----> 2
Start index: 1 End index: 2 -----> +
Start index: 2 End index: 4 -----> 30
Start index: 4 End index: 5 -----> *
Start index: 5 End index: 6 -----> 4
Start index: 6 End index: 7 -----> +
Start index: 7 End index: 8 -----> (
Start index: 8 End index: 9 -----> 5
Start index: 9 End index: 10 -----> +
Start index: 10 End index: 11 -----> 6
Start index: 11 End index: 12 -----> )
If you are not interested in positions of your tokens you can also split
before or after each of +
-
*
/
(
)
like
String s = "2+30*4+(5+6)*7";
String[] tokens = s.split("(?<=[+\\-*/()])|(?=[+\\-*/()])");
for (String token : tokens)
System.out.println(token);
output:
2
+
30
*
4
+
(
5
+
6
)
*
7