除了单个空格之外,在空格上拆分字符串

时间:2022-08-22 12:46:03

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

我如何为单个空间提供例外。即在空间上分开,除了单个空间

4 个解决方案

#1


9  

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.

您可以检查Pattern类中的量词语法。

#2


1  

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.

请注意,空白字符不仅仅是一个简单的空白。

#3


1  

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

will do the job.

会做的。

For example:

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

This will return an array with length 3.

这将返回长度为3的数组。

The following would be the output.

以下是输出。

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

I hope this answers your question.

我希望这回答了你的问题。

#4


0  

If you literally want to exclude a single space, as opposed to other types of whitespace, then you'll need the following:

如果你真的想要排除单个空格,而不是其他类型的空格,那么你需要以下内容:

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

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

这通过从\ s内置字符类中减去空格来构造字符类。

#1


9  

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.

您可以检查Pattern类中的量词语法。

#2


1  

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.

请注意,空白字符不仅仅是一个简单的空白。

#3


1  

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

will do the job.

会做的。

For example:

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

This will return an array with length 3.

这将返回长度为3的数组。

The following would be the output.

以下是输出。

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

I hope this answers your question.

我希望这回答了你的问题。

#4


0  

If you literally want to exclude a single space, as opposed to other types of whitespace, then you'll need the following:

如果你真的想要排除单个空格,而不是其他类型的空格,那么你需要以下内容:

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

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

这通过从\ s内置字符类中减去空格来构造字符类。