我有我的正则表达式模式:[0-9]+ km\/h
这是我的测试字符串:Northernly winds 10 to 20 km/h decreasing to 5 to 10 km/h in the afternoon.
此模式适用于在线正则表达式测试器工具,但是在下面的代码中失败:
val description = "Northernly winds 10 to 20 km/h decreasing to 5 to 10 km/h in the afternoon."
val pattern = Pattern.compile("[0-9]+ km/h")
val matcher = pattern.matcher(description)
return matcher.matches() // returns false :(
matcher.matches()
返回假的原因是什么?
下面经过修改的java程序可以与提供的正则表达式一起正常工作
String description = "Northernly winds 10 to 20 km/h decreasing to 5 to 10 km/h in the afternoon.";
Pattern pattern = Pattern.compile("[0-9]+ km/h");
Matcher matcher = pattern.matcher(description);
System.out.println( matcher.find());
下面的代码说明何时可以使用matchs函数,匹配项将搜索整个单词。
String description = "20 km/h";
Pattern pattern = Pattern.compile("[0-9]+ km/h");
Matcher matcher = pattern.matcher(description);
System.out.println( matcher.matches());