0

I'm trying to find a way to split a String in Java without ignoring the spaces. After searching I've found a way to do it in python :

re.split(r"(\s+)", "This is the string I want to split")

would result in:

['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] 

How can this be done in java?

Jared
  • 159
  • 2
  • 3
  • 12

1 Answers1

3

Yep, you need to use lookarounds.

string.split("(?<=\\s+)|(?=\\s+)");
  • (?<=\\s+) Matches the boundary which exists after one or more spaces.

  • | OR

  • (?=\\s+) Matches the boundary which exits before one or more spaces.

  • Splitting according to the matched boundary will give you the desired output.

Example:

String s = "This is the string I want to split";
String[] parts = s.split("(?<=\\s+)|(?=\\s+)"); 
System.out.println(Arrays.toString(parts));

Output:

[This,  , is,  , the,  , string,  , I,  , want,  , to,  , split]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274