0

我对这段代码有一点问题:

String[] paragraph;
if(paragraph[searchKeyword_counter].matches("(.*)(\\b)"+"is"+"(\\b)(.*)")){

如果我没有弄错使用.matches()和搜索字符串中的特定字符,我需要 a.*但我想要发生的是搜索一个字符而不将其与另一个单词匹配。例如is,我要搜索的关键字我不希望它与包含is类似字符的单词匹配ship, his, this。所以我用于\b边界,但上面的代码对我不起作用。

例子:

String[] Content= {"is,","his","fish","ish","its","is"};
String keyword = "is";
for(int i=0;i<Content.length;i++){
    if(content[i].matches("(.*)(\\b)"+keyword+"(\\b)(.*)")){
         System.out.println("There are "+i+" is.");
    }
}

我想在这里发生的是它只会匹配is is,但不匹配his fish。所以is应该与is, and is我希望它匹配的意思匹配,即使字符在非字母数字字符和空格旁边。

上面的代码有什么问题?

如果其中一个内容有大写字符示例IS,并且与 比较is,它将不匹配。如果我错了,请纠正我。如何在不更改源内容的情况下将小写字符与大写字符匹配?

4

2 回答 2

0
String string = "...";
String word = "is";

Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b");
Matcher m = p.matcher(string);
if (m.find()) {
  ...
}
于 2012-11-06T14:48:59.987 回答
0

只需添加这样的空格:

假设消息等于您的内容字符串,而模式是您的关键字

 if ((message).matches(".* " + pattern + " .*")||(message).matches("^" + pattern + " .*")
            ||(message).matches(".* " + pattern + "$")) {
于 2015-01-30T11:35:47.723 回答