简体   繁体   English

使用正则表达式在正好一个空格处分割字符串

[英]Splitting a string using regex at exactly one space

I am trying to split a string using spaces but only if there is one space. 我试图使用空格拆分字符串,但前提是只有一个空格。

For example I have the following. 例如,我有以下内容。

String s = "THIS IS A  TEST";

I want to take the result "THIS", "IS", "A TEST". 我要取结果“ THIS”,“ IS”,“ A TEST”。 How to form the regex to do the job? 如何形成正则表达式来完成这项工作?

Use lookarounds: 使用环顾:

(?<!\s)(\s)(?!\s)

This regex matches space that's not followed and not preceded by a space. 此正则表达式匹配没有空格且前面没有空格的空格。

In Java, it'll look: 在Java中,外观如下:

"THIS IS A  TEST".split("(?<!\\s)(\\s)(?!\\s)");

Explanation: 说明:

  • The regex (?<!a)b matches "b" that's not preceded by an "a" 正则表达式(?<!a)b相匹配,这不是一个“一” 开头 “B”
  • The regex b(?!a) matches "b" that's not followed by an "a" 正则表达式b(?!a)符合“B”,这不是一个“一”

Further reading: 进一步阅读:

Since the argument to split() is a regular expression, you can look for one or more spaces (" +") instead of just one space (" "). 由于split()的参数是一个正则表达式,因此您可以查找一个或多个空格(“ +”)而不是一个空格(“”)。

String[] array = s.split(" +"); String [] array = s.split(“ +”);

You can also add and argument to limit the number of slips you want to split the string into. 您还可以添加和参数来限制要将字符串拆分成的支票数量。

String[] array = s.split(" +", N ); String [] array = s.split(“ +”,N);

Where N is the number of splits you want to divide the string into. 其中N是您想要将字符串分成的分割数。

您可以尝试使用单词边界的此正则表达式。

string.split("\\b\\s\\b");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM