有没有办法检查子字符串是否包含整个 WORD,而不是子字符串。
设想以下场景:
public class Test {
public static void main(String[] args) {
String[] text = {"this is a", "banana"};
String search = "a";
int counter = 0;
for(int i = 0; i < text.length; i++) {
if(text[i].toLowerCase().contains(search)) {
counter++;
}
}
System.out.println("Counter was " + counter);
}
}
计算结果为
Counter was 2
这不是我要找的,因为数组中只有一个单词“a”的实例。
我的阅读方式如下:
if 测试在 text[0] 中找到一个“a”,该“a”对应于“this is [a]”。但是,它还会在“banana”中发现“a”的出现,从而增加计数器。
如何解决这个问题,只包含单词“a”,而不包含包含 a 的子字符串?
谢谢!
最佳答案
您可以使用正则表达式,使用 Pattern.quote转义任何特殊字符。
String regex = ".*\\b" + Pattern.quote(search) + "\\b.*"; // \b is a word boundary
int counter = 0;
for(int i = 0; i < text.length; i++) {
if(text[i].toLowerCase().matches(regex)) {
counter++;
}
}
请注意,这还会在 “这是 a; 暂停”
或 “寻找 a?”
中找到 “a”
,其中 a
后面没有空格。
关于java - 检查字符串是否包含单词(不是子字符串!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36793397/