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

nkkqxpd9  于 2021-07-12  发布在  Java
关注(0)|答案(5)|浏览(417)

我正在处理字符串,如果两个字符/元素之间有空格,我需要将它们分开。我已经看到一个以前的职位,所以差不多一样,但它仍然没有为我的预期工作尚未。如您所想,我可以只检查字符串是否包含(“”),然后再检查空格周围的子字符串。然而,我的字符串可能在结尾包含无数的空格,尽管字符之间没有空格。因此,我的问题是“如何检测两个字符之间的空白(数字也是)”?
//字符串中包含数字的示例

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

zpjtge221#

你会用 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"]

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

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

s6fujrry2#

如果使用regex,肯定的lookahead和lookback也可以工作
(?<=\w)\s(?=\w) \w :单词字符
[a-zA-Z_0-9] \\s :空白 (?<=\\w)\\s :正向lookback,如果空格前面有
\w \\s(?=\\w) :正向展望,如果空格后跟 \w ```
List 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!

rjzwgtxy

rjzwgtxy3#

您的模式不能按预期工作的原因是 ^(\\d [\\d\\d] )*\\d$ 可以简化为 (\\d \\d )*\\d$ 开始时重复0次或更多次括号之间的内容。
然后它匹配字符串末尾的一个数字。由于重复次数为0次或更多次,因此它是可选的,并且也只匹配一个数字。
如果要检查两个非空白字符之间是否有单个空格:

\\S \\S

正则表达式演示| java演示

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

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

pod7payv4#

使用

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 模式匹配一个非空白字符,然后匹配一个或多个空白字符,然后再匹配一个非空白字符。

nnsrf1az

nnsrf1az5#

下面是最简单的方法:

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

相关问题