Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split() a String while maintaining whitespace [duplicate]

Tags:

java

regex

How do you split a string of words and retain whitespaces?

Here is the code:

String words[] = s.split(" "); 

String s contains: hello world

After the code runs, words[] contains: "hello" "" world

Ideally, it should not be an empty string in the middle, but contain both whitespaces: words[] should be: "hello" " " " " world

How do I get it to have this result?

like image 621
Rock Lee Avatar asked Jul 07 '15 15:07

Rock Lee


People also ask

How do you split a string but keep the spaces?

To split a string keeping the whitespace, call the split() method passing it the following regular expression - /(\s+)/ . The regular expression uses a capturing group to preserve the whitespace when splitting the string.

How do you split a string into white space in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

How split a string by space in C#?

String. Split can use multiple separator characters. The following example uses spaces, commas, periods, colons, and tabs as separating characters, which are passed to Split in an array . The loop at the bottom of the code displays each of the words in the returned array.


2 Answers

You could use lookahead/lookbehind assertions:

String[] words = "hello  world".split("((?<=\\s+)|(?=\\s+))");

where (?<=\\s+) and (?=\\s+) are zero-width groups.

like image 112
Reimeus Avatar answered Oct 25 '22 14:10

Reimeus


If you can tolerate both white spaces together in one string, you can do

String[] words = s.split("\\b");

Then words contains ("hello", " ", "world").

like image 38
dcsohl Avatar answered Oct 25 '22 14:10

dcsohl