如何根据以下代码确定模式名称:
Matcher m;
if( ((m = PATTERN_1.matcher(text)).find()) ||
((m = PATTERN_2.matcher(text)).find()) )
{
System.out.println("Pattern: " + m.patternName?); // how can I determine the matched pattern?
// i.e - "Pattern: PATTERN_1"
}
答案 0 :(得分:3)
我相信Matcher#pattern()
应该适合你。
考虑以下代码:
Matcher m;
Pattern PATTERN_1=Pattern.compile("\\d+");
Pattern PATTERN_2=Pattern.compile("[a-z]+");
String text="abc";
if( ((m = PATTERN_1.matcher(text)).find()) ||
((m = PATTERN_2.matcher(text)).find()) ) {
System.out.println("PATTERN: " + m.pattern());
}
// prints: PATTERN: [a-z]+