检查字符串中两个元素之间是否有空白。

huangapple go评论75阅读模式
英文:

Checking if there is whitespace between two elements in a String

问题

我正在处理字符串,需要在两个字符/元素之间有空格时将它们分开。我在Stack Overflow上看到过一个关于相同问题的帖子,但是对我来说还没有按预期工作。正如你所想,我可以检查字符串是否包含(" "),然后在空格周围进行子字符串分割。然而,尽管我的字符串在字符之间没有空格,但可能在末尾包含无数个空格。因此,我的问题是:“如何检测两个字符(数字也是如此)之间的空格?”

// 使用数字的示例

String test = "2 2";

final Pattern P = Pattern.compile("^(\d [\d\d] )*\d$");

final Matcher m = P.matcher(test);

if (m.matches()) {
System.out.println("两个字符之间有空格!");
}

英文:

I am working with Strings where I need to separate two chars/elements if there is a whitespace between them. I have seen a former post on SO about the same however it still has not worked for me as intended yet. As you would assume, I could just check if the String contains(" ") and then substring around the space. However my strings could possibly contains countless whitespaces at the end despite not having whitespace in between characters. Hence my question is "How do I detect a whitespace between two chars (numbers too) " ?

//Example with numbers in a String

    String test = "2 2";

    final Pattern P = Pattern.compile("^(\\d [\\d\\d] )*\\d$");

    final Matcher m = P.matcher(test);

    if (m.matches()) {
        System.out.println("There is between space!");
    }

答案1

得分: 3

你会使用 String.strip() 来删除任何前导或尾随的空格,然后使用 String.split()。如果存在空格,则数组的长度将为2或更多。如果没有空格,则长度为1。

示例:

String test = "    2 2   ";
test = test.strip(); // 删除空格,test 现在是 "2 2"
String[] testSplit = test.split(" "); // 拆分字符串,testSplit 为 ["2", "2"]
if (testSplit.length >= 2) {
    System.out.println("存在空格!");
} else {
    System.out.println("没有空格");
}

如果您需要一个特定长度的数组,还可以指定拆分的限制。例如:

"a b c".split(" ", 2); // 返回 ["a", "b c"]

如果您想要仅使用正则表达式的解决方案,以下正则表达式匹配由单个空格分隔的任意两组字符,前后可以有任意数量的空格:

\s*(\S+\s\S+)\s*
英文:

You would use String.strip() to remove any leading or trailing whitespace, followed by String.split(). If there is a whitespace, the array will be of length 2 or greater. If there is not, it will be of length 1.

Example:

String test = "    2 2   ";
test = test.strip(); // Removes whitespace, test is now "2 2"
String[] testSplit = test.split(" "); // Splits the string, testSplit is ["2", "2"]
if (testSplit.length >= 2) {
    System.out.println("There is whitespace!");
} else {
    System.out.println("There is no whitespace");
}

If you need an array of a specified length, you can also specify a limit to split. For example:

"a b c".split(" ", 2); // Returns ["a", "b c"]

If you want a solution that only uses regex, the following regex matches any two groups of characters separated by a single space, with any amount of leading or trailing whitespace:

\s*(\S+\s\S+)\s*

答案2

得分: 1

正向先行断言和正向后行断言也可以在使用正则表达式 (?<=\\w)\\s(?=\\w) 时起作用。

  • \w:一个单词字符 [a-zA-Z_0-9]
  • \\s:空白字符
  • (?<=\\w)\\s:正向后行断言,匹配前面是 \w 的空白字符
  • \\s(?=\\w):正向先行断言,匹配后面是 \w 的空白字符
List<String> testList = Arrays.asList("2 2", " 245  ");

Pattern p = Pattern.compile("(?<=\\w)\\s(?=\\w)");
for (String str : testList) {
    Matcher m = p.matcher(str);

    if (m.find()) {
        System.out.println(str + "\t: 有空格!");
    } else {
        System.out.println(str + "\t: 没有空格!");
    }
}

输出:

2 2	: 有空格!
 245  	: 没有空格!
英文:

Positive lookahead and lookbehind may also work if you use the regex (?&lt;=\\w)\\s(?=\\w)

  • \w : a word character [a-zA-Z_0-9]
  • \\s : whitespace
  • (?&lt;=\\w)\\s : positive lookbehind, matches if a whitespace preceeded by a \w
  • \\s(?=\\w) : positive lookahead, matches if a whitespace followed by a \w

List&lt;String&gt; testList = Arrays.asList(&quot;2 2&quot;, &quot; 245  &quot;);

Pattern p = Pattern.compile(&quot;(?&lt;=\\w)\\s(?=\\w)&quot;);
for (String str : testList) {

	Matcher m = p.matcher(str);

	if (m.find()) {
		System.out.println(str + &quot;\t: There is a space!&quot;);
	} else {
		System.out.println(str + &quot;\t: There is not a space!&quot;);
	}
}

Output:

2 2	: There is a space!
 245  	: There is not a space!

答案3

得分: 1

你的模式未按预期工作的原因是因为 ^(\\d [\\d\\d] )*\\d$,它可以简化为 (\\d \\d )*\\d$,它从重复0次或更多次括号中的内容开始。

然后它在字符串末尾匹配一个数字。由于重复次数为0次或更多次,它是可选的,也可以匹配单个数字。

<hr>

如果你想检查在两个非空白字符之间是否有单个空格:

\\S \\S

正则表达式示例 | Java示例

final Pattern P = Pattern.compile(&quot;\\S \\S&quot;);
final Matcher m = P.matcher(test);

if (m.find()) {
    System.out.println(&quot;两者之间有空格!&quot;);
}
英文:

The reason you pattern does not work as expected is because ^(\\d [\\d\\d] )*\\d$ which can be simplified to (\\d \\d )*\\d$ starts by repeating 0 or more times what is between the parenthesis.

Then it matches a digit at the end of the string. As the repetition is 0 or more times, it is optional and it would also match just a single digit.

<hr>

If you want to check if there is a single space between 2 non whitespace chars:

\\S \\S

Regex demo | Java demo

final Pattern P = Pattern.compile(&quot;\\S \\S&quot;);
final Matcher m = P.matcher(test);

if (m.find()) {
    System.out.println(&quot;There is between space!&quot;);
}

答案4

得分: 0

这是你可以完成它的最简单方法:

String testString = "   查找是否有空格。   ";
testString.trim(); // 这会删除所有前导和尾随空格
testString.contains(" "); // 检查字符串是否仍然包含空格

你还可以在一行中使用链接这两个方法的简写方法:

String testString = "   查找是否有空格。   ";
testString.trim().contains(" ");
英文:

Here is the simplest way you can do it:

String testString = &quot;   Find if there is a space.   &quot;;
testString.trim(); //This removes all the leading and trailing spaces
testString.contains(&quot; &quot;); //Checks if the string contains a whitespace still

You can also use a shorthand method in one line by chaining the two methods:

String testString = &quot;   Find if there is a space.   &quot;;
testString.trim().contains(&quot; &quot;);

</details>



# 答案5
**得分**: 0

```java
String text = "2 2";
Matcher m = Pattern.compile("\\S\\s+\\S").matcher(text.trim());
if (m.find()) {
    System.out.println("Space detected.");
}

在这个Java代码示例中,text.trim() 将会移除字符串开头和结尾的空白字符,\S\s+\S 模式用于匹配非空白字符,然后是一个或多个空白字符,然后再是一个非空白字符。

英文:

Use

String text = &quot;2 2&quot;;
Matcher m = Pattern.compile(&quot;\\S\\s+\\S&quot;).matcher(text.trim());
if (m.find()) {
    System.out.println(&quot;Space detected.&quot;);
}

Java code demo.

text.trim() will remove leading and trailing whitespaces, \S\s+\S pattern matches a non-whitespace, then one or more whitespace characters, and then a non-whitespace character again.

huangapple
  • 本文由 发表于 2020年8月19日 21:45:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63488382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定