我有一行可以匹配多个关键字.整个关键字应该匹配.
例,
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");
}
Run Code Online (Sandbox Code Playgroud)
这段代码工作正常.但如果要匹配的关键字过多,则该行会增长. 有没有优雅的方式编写相同的代码? 谢谢
你可以写一个这样的正则表达式:
Country0|Country1|Country2
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
String str = "This is an example text like Australia India England";
if (Pattern.compile("Australia|India|England").matcher(str).find())
System.out.println("Matches");
Run Code Online (Sandbox Code Playgroud)
如果您想知道哪些国家/地区匹配:
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());
}
Run Code Online (Sandbox Code Playgroud)
输出:
Matches: Australia
Matches: India
Matches: England
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2143 次 |
| 最近记录: |