I'm looking for a regex that will split a string as follows:
String input = "x^(24-3x)";
String[] signs = input.split("regex here");
for (int i = 0; i < signs.length; i++) { System.out.println(sings[i]); }
with the output resulting in:
"x", "^", "(", "24", "-", "3", "x", ")"
The string is split at every character. However, if there are digits next to each other, they should remain grouped in one string.
You can use this lookaround based regex:
String[] signs = input.split("(?<!^)(?=\\D)|(?<=\\D)");
RegEx Demo
RegEx Breakup
(?<!^)(?=\\D) # assert if next char is non-digit and we're not at start
| # regex alternation
(?<=\\D) # assert if previous character is a non-digit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With