BAST23
BAST23

Reputation: 75

Regex Split by spaces but ignoring spaces between words

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

Answers (2)

user unknown
user unknown

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")
  • first break, when blank between two digits or digit and String
  • then break that, when a blank between char and digit

Upvotes: 1

Allan
Allan

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

Related Questions