java我想将Matcher变量存储为字符串
我希望我的应用程序将任何匹配项读取为字符串
Scanner reader = new Scanner(System.in);
System.out.println("Problem 1: Create a heading using h1 tag");
String input = reader.nextLine();
Pattern regex = Pattern.compile("<[a-z][0-9]>");
Matcher m = regex.matcher(input);
if(m.find()){
String meme = m.group(0);
System.out.println(meme);
if(meme == "<h1>"){
System.out.println("Found a string.");
}
else{
System.out.println("No string found.");
}
}
else{
System.out.println("No closing tag.");
}
例如我
输入<..h1..>
(忽略点)
但是输出总是No string found
,即使我设置了meme == <..h1..>
。如何将其转换为字符串
# 1 楼答案
我认为你的代码的问题就在这一行
应该是的
# 2 楼答案
问题出在{}
因为相等运算符(
==
)基于引用而不是值进行比较,所以这实际上是在比较两个单独的字符串:meme
和"<h1>"
。相反,请使用: