在程序中,我试图在内容中寻找模式。如果在用户拍摄的字符串中找到任何模式H Q 9,则应打印YES
其他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");
}
答案 0 :(得分:4)
你的正则表达式错误 - H*
表示"任意数量的Hs,包括零",以及其他正则表达式。
因此,.*H*.
意味着你的文本应该包含任意数量的"某些",然后是任意数量的Hs(或者没有,因为"零Hs"是也允许),然后是一个任意的字母。
codeforces
符合这些标准,因为它包含任意数量的字母,没有H,并以任意字母结尾。
你的正则表达式将匹配任何至少有一次字符的输入。
答案 1 :(得分:3)
使用三个正则表达式是多余的。我建议只使用一个。
我还重构并重新格式化了代码。
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].*
执行以下操作:它搜索与方括号内找到的字符相等的任何字符:
答案 2 :(得分:1)
虽然有人已经解释了这个问题(我不想从别人那里得到赞助),但这里有一些建议可以减少,更重要的是测试你的代码
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
作为一个简单的测试,删除正则表达式中的.*
,重新编译并查看输出。你会发现它们是必需的。