检查字符串中两个元素之间是否存在空格

问题描述

我正在使用Strings,如果它们之间有空格,则需要分隔两个字符/元素。我曾经看到过关于SO的以前的帖子,但是它仍然没有按预期工作。如您所料,我只需要检查字符串是否包含(“”),然后检查空格周围的子字符串。但是,尽管字符之间没有空格,但我的字符串末尾可能包含无数个空格。因此,我的问题是“如何检测两个字符(也包括数字)之间的空格”?

//在字符串中带有数字的示例

    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!");
    }

解决方法

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

示例:

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");
}

如果需要指定长度的数组,还可以指定分割限制。例如:

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

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

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

如果使用正则表达式(?<=\\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: There is a space!");
    } else {
        System.out.println(str + "\t: There is not a space!");
    }
}

输出:

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

模式设置无法按预期运行的原因是因为可以简化为^(\\d [\\d\\d] )*\\d$的{​​{1}}是通过重复0次或多次插入括号之间的内容来开始的。

然后它匹配字符串末尾的数字。由于重复是0次或多次,因此它是可选的,并且也只能匹配一位数字。


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

(\\d \\d )*\\d$

Regex demo | Java demo

\\S \\S
,

使用

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

Java code demo

text.trim()将删除开头和结尾的空白,\S\s+\S模式匹配一​​个非空白,然后匹配一个或多个空白字符,然后再次匹配一个非空白字符。

,

这是最简单的方法:

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

您还可以通过链接两种方法在一行中使用速记方法:

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