Separate a string in space except for one space

I split the string into spaces using the following

myString.split("\\s+"); 

How to provide an exception for one space. ie split into space, excluding single space

+4
source share
4 answers

Like this:

 myString.split("\\s{2,}"); 

or like that

 myString.split(" \\s+"); // notice the blank at the beginning. 

It depends on what you really want, which is unclear after reading the question.

You can check the syntax of the quantifier in the Pattern class.

+8
source

You can use a template like

 myString.split("\\s\\s+"); 

This only matches a space character followed by a space character.

Note that the space character is more than a simple space.

+1
source
 "Your String".split("\\s{2,}"); 

will do the job.

For instance:

 String str = "I am a String"; String []strArr = str.split("\\s{2,}"); 

This will return an array of length 3.

The following will be the conclusion.

 strArr[0] = "I am" strArr[1] = "a" strArr[2] = "String" 

Hope this answers your question.

+1
source

If you literally want to exclude one space, unlike other types of spaces, you will need the following:

 s.split("\\s{2,}|[\\s&&[^ ]]") 

This creates a character class by subtracting the space from the built-in character class \s .

0
source

Source: https://habr.com/ru/post/1490263/


All Articles