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



我正在使用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+sS+)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 [\d\d] )*\d$从重复0次或更多次括号之间的内容开始。

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


如果您想检查两个非空白字符之间是否有一个空格:

\S \S

Regex演示| Java演示

final Pattern P = Pattern.compile("\S \S");
final Matcher m = P.matcher(test);
if (m.find()) {
System.out.println("There is between space!");
}

以下是最简单的方法:

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

使用

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()将删除前导和尾部空白,Ss+S模式匹配非空白,然后匹配一个或多个空白字符,然后再次匹配非空白字符。

最新更新