簡體   English   中英

字符串匹配,Java

[英]String Matches, Java

我對這段代碼有一個問題:

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

如果我沒有錯誤地使用.matches()並搜索字符串中的特定字符,我需要一個.*但我想要發生的是搜索一個字符而不將其與另一個單詞匹配。 例如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,匹配is is,而不是與his fish匹配。 所以is應該與is, and is匹配,這意味着即使字符在非字母數字字符和空格旁邊,我也希望它匹配。

上面的代碼有什么問題?

如果內容之一具有大寫字符例如什么IS ,它是用比較is ,這將是無法比擬的。 如果我錯了,請糾正我。 如何在不更改源內容的情況下將小寫字符與大寫字符匹配?

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

Pattern p = Pattern.compile("\\b" + Pattern.quote(word) + "\\b");
Matcher m = p.matcher(string);
if (m.find()) {
  ...
}

只需添加這樣的空格:

假設消息等於您的內容字符串,模式是您的關鍵字

 if ((message).matches(".* " + pattern + " .*")||(message).matches("^" + pattern + " .*")
            ||(message).matches(".* " + pattern + "$")) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM