Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for splitting at every character but keeping numbers together

Tags:

java

regex

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.

like image 402
Zi1mann Avatar asked Sep 27 '22 00:09

Zi1mann


1 Answers

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
like image 116
anubhava Avatar answered Oct 12 '22 23:10

anubhava