这个问题在这里已有答案:
我陷入一个简单的问题,我想检查是否有任何一个词:he,be,de出现在我的文本中。
所以我使用'|'创建了模式(存在于代码中)象征OR,然后我匹配我的文字。但这场比赛给了我错误的结果(在印刷声明中)。
我尝试使用Regex搜索在Notepad ++中进行相同的匹配,它在那里工作,但在Java中给出了FALSE(不匹配)。 C
public class Del {
public static void main(String[] args) {
String pattern="he|be|de";
String text= "he is ";
System.out.println(text.matches(pattern));
}
}
任何人都可以建议我做错了什么。谢谢
这是因为你试图匹配整个字符串而不是要找到的部分。例如,此代码将发现只有字符串的一部分符合当前的正则表达式:
Matcher m = Pattern.compile("he|be|de").matcher("he is ");
m.find(); //true
当你想匹配整个字符串并检查该字符串是否包含he | be | de时使用此正则表达式.*(he|be|de).*
.
表示任何符号,*
是先前的符号可能存在零次或多次。例:
"he is ".matches(".*(he|be|de).*"); //true
String regExp="he|be|de";
Pattern pattern = Pattern.compile(regExp);
String text = "he is ";
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());