Reputation: 75
How can I do regex Split on a string on whitespace but ignoring the whitespace between words?
The string looks like:
1 IT1103 Kabellose Maus Freemove 5 23.07.2018 30 150,00
I want to split the string like and save it into DataTable
1
IT1103
Kabellose Maus Freemove
5
23.07.2018
30
150,00
Could anyone help please?
Thanks Bonnie
Upvotes: 1
Views: 647
Reputation: 36229
Simpler than Allans solution, but more verbose:
String tmp = input.replaceAll ("([0-9]) ([0-9a-zA-Z])", "\1\n\2")
String out = tmp.replaceAll ("([a-zA-Z]) ([0-9])", "\1\n\2")
Upvotes: 1
Reputation: 12438
You can use the following code:
String input ="1 IT1103 Kabellose Maus Freemove 5 23.07.2018 30 150,00";
final String PATTERN = "(?<=\\d)\\s|\\s(?=\\d)";
String[] array = input.split(PATTERN);
for(String str : array)
{
System.out.println(str);
}
output:
1
IT1103
Kabellose Maus Freemove
5
23.07.2018
30
150,00
regex: https://regex101.com/r/MN6juN/2
explanations:
(?<=\\d)\\s|\\s(?=\\d)
is a regex that will take into account only spaces that are followed/preceded by a digit, therefore Kabellose Maus Freemove
will be treated as a whole string.
Upvotes: 2