我正在尝试制作一种模式,该模式可以从JAVA中的字符串给我小时和分钟。 我尝试执行的一个或多个示例都失败了。
可以有以下组合。
10分钟
Pattern p = Pattern.compile("([\\d]+)\\s+[hour|hours]*\\s*([\\d]*)[^\\d]*");
Matcher m = p.matcher("8 hours 2 minutes");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
System.out.println("found");
System.out.println(m.group(1)); // hours
System.out.println(m.group(2)); // minutes
}
答案 0 :(得分:0)
您可以使用此正则表达式,并从匹配的适当组中提取小时和/或分钟。
^(?=.)(?:(?<hours>\d+) *hours?)?(?: *(?<minutes>\d+) *minutes?)?$
尽管我已经命名了这些组,以使其更易于访问,但实际上并不是必需的。即使没有命名组,group1也将始终捕获小时,而group2将始终捕获分钟,无论您的数据包含什么,是仅小时还是仅几分钟,或两者兼而有之。
还请签出此Java代码。
List<String> list = Arrays.asList("1 hour","2 hours","1 hour 20 minutes","3 hours 30 minutes","3 hours 1 minute","1 hour 1 minute","1 minute","10 minutes");
Pattern p = Pattern.compile("^(?=.)(?:(?<hours>\\d+) *hours?)?(?: *(?<minutes>\\d+) *minutes?)?$");
list.stream().forEach(x -> {
Matcher m = p.matcher(x);
if (m.matches()) {
System.out.println(x + " ----> Hours: " + m.group("hours") + ", Minutes: " + m.group("minutes"));
} else {
System.out.println(x + " ----> Didn't match");
}
});
打印
1 hour ----> Hours: 1, Minutes: null
2 hours ----> Hours: 2, Minutes: null
1 hour 20 minutes ----> Hours: 1, Minutes: 20
3 hours 30 minutes ----> Hours: 3, Minutes: 30
3 hours 1 minute ----> Hours: 3, Minutes: 1
1 hour 1 minute ----> Hours: 1, Minutes: 1
1 minute ----> Hours: null, Minutes: 1
10 minutes ----> Hours: null, Minutes: 10