Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string on space except for single space

I was splitting a string on white spaces using the following

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

How do i provide exception for single space. i.e split on space except for single space

like image 646
John Avatar asked Jul 08 '13 11:07

John


People also ask

How do you split a string where there is a space?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do you split a string including space in Python?

Python String split() MethodThe 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 you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.


2 Answers

Like this:

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

or like this,

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

It depends on what you really want, which is not clear by reading the question.

You can check the quantifier syntax in the Pattern class.

like image 65
jlordo Avatar answered Sep 24 '22 19:09

jlordo


You can use a pattern like

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

This only matches if a whitespace character is followed by further whitespace charactes.

Please note that a whitespace character is more than a simple blank.

like image 35
Uwe Plonus Avatar answered Sep 20 '22 19:09

Uwe Plonus