我有一行可以匹配多个关键字。整个关键字应匹配。
例,
String str = "This is an example text for matching countries like Australia India England";
if(str.contains("Australia") ||
str.contains("India") ||
str.contains("England")){
System.out.println("Matches");
}else{
System.out.println("Does not match");
}
此代码可以正常工作。但是,如果要匹配的关键字过多,则该行会增加。是否有任何优雅的方式编写相同的代码?
谢谢
最佳答案
您可以编写这样的正则表达式:
Country0|Country1|Country2
像这样使用它:
String str = "This is an example text like Australia India England";
if (Pattern.compile("Australia|India|England").matcher(str).find())
System.out.println("Matches");
如果您想知道哪个国家匹配:
public static void main(String[] args) {
String str = "This is an example text like Australia India England";
Matcher m = Pattern.compile("Australia|India|England").matcher(str);
while (m.find())
System.out.println("Matches: " + m.group());
}
输出:
Matches: Australia
Matches: India
Matches: England