[英]pattern matching in java using regex
在程序中,我試圖在內容中尋找模式。 如果在用戶獲取的字符串中找到任何模式 HQ 9 ,則應打印YES
else NO
。 所以我用了三個 bool flag1
flag2
flag3
。 如果輸入是codeforces
我的代碼會給出錯誤的輸出。 所需的輸出是NO
而不是YES
。
public static void main(String[] args) {
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
Scanner in = new Scanner(System.in);
String s = in.nextLine();
String text = s;
String pat1 = ".*H*.";
String pat2 = ".*Q*.";
String pat3 = ".*9*.";
//boolean isMatch = Pattern.matches(pattern, content);
flag1 = Pattern.matches(pat1, text);
flag2 = Pattern.matches(pat2, text);
flag3 = Pattern.matches(pat3,text);
if (flag1 == true || flag2 == true || flag3 == true)
System.out.println("YES");
else
System.out.println("NO");
}
您的正則表達式是錯誤的 - H*
表示“任意數量的 H,包括零”,對於其他兩個正則表達式也是如此。
因此, .*H*.
意味着您的文本應該包含任意數量的“某物”,然后是任意數量的 Hs(或沒有,因為也允許“零 Hs”),然后是任意字母。
codeforces
滿足這些標准,因為它包含任意數量的字母,沒有 H 並以任意字母結尾。
您的正則表達式將匹配至少有一次字符的任何輸入。
使用三個正則表達式是多余的。 我建議只使用一個。
我還重構並重新格式化了您的代碼。
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean matches = Pattern.matches(".*[HQ9].*", s);
if (matches)
{
System.out.println("YES");
} else
{
System.out.println("NO");
}
}
您可以進一步壓縮該方法:
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String s = in.nextLine();
boolean matches = Pattern.matches("[HQ9]", s);
System.out.println(matches ? "YES" : "NO");
}
正則表達式.*[HQ9].*
執行以下操作:它搜索與方括號內找到的字符相等的任何字符:
雖然有人已經解釋了這個問題(我不想從其他人那里獲得榮譽),但這里有一些建議可以減少和更重要的是測試你的代碼
import java.util.regex.Pattern;
class Test75B {
public static final String[] TESTS = {
"codeforces",
"Back to Headquarters",
"A cat has nine lives",
"A cat has 9 lives",
"Is it a Query or a Quarry?",
"How Can You Quote 4+5=9!"
};
public static void main(String[] args) {
for (String text: TESTS) {
boolean flag1=false;
String pat1= ".*[HQ9].*";
System.out.println(text);
flag1=Pattern.matches(pat1, text);
System.out.println( flag1 ? "YES" : "NO");
}
}
}
這是我得到的輸出
codeforces
NO
Back to Headquarters
YES
A cat has nine lives
NO
A cat has 9 lives
YES
Is it a Query or a Quarry?
YES
How Can You Quote 4+5=9!
YES
作為一個簡單的測試,刪除正則表達式中的.*
,重新編譯並查看輸出。 您會看到它們是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.