在 Java 中,我想使用正则表达式解析格式为“MM/DD/YYYY”的日期字符串。我尝试用括号创建捕获组,但它似乎不起作用。它只返回整个匹配的字符串——而不是“MM”、“DD”和“YYYY”组件。
public static void main(String[] args) {
Pattern p1=Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})");
Matcher m1=p1.matcher("04/30/1999");
// Throws IllegalStateException: "No match found":
//System.out.println("Group 0: "+m1.group(0));
// Runs only once and prints "Found: 04/30/1999".
while (m1.find()){
System.out.println("Found: "+m1.group());
}
// Wanted 3 lines: "Found: 04", "Found: 30", "Found: 1999"
}
Run Code Online (Sandbox Code Playgroud)
group带有参数 ( m1.group(x))的 " " 函数似乎根本不起作用,因为无论我给它什么索引,它都会返回异常。循环find()'s 仅返回单个完整匹配“04/30/1999”。正则表达式中的括号好像完全没用!
这在 Perl 中很容易做到:
my $date = "04/30/1999";
my ($month,$day,$year) = $date =~ m/(\d{2})\/(\d{2})\/(\d{4})/;
print "Month: ",$month,", day: ",$day,", year: ",$year;
# Prints:
# Month: 04, day: 30, year: 1999
Run Code Online (Sandbox Code Playgroud)
我错过了什么?Java 正则表达式是否无法像 Perl 一样解析出捕获组?
m1.find()先调用,然后使用m1.group(N)
matcher.group()或matcher.group(0)返回整个匹配的文本。
matcher.group(1)返回与第一组匹配的文本。
matcher.group(2)返回与第二组匹配的文本。
...
代码
Pattern p1=Pattern.compile("(\\d{2})/(\\d{2})/(\\d{4})");
Matcher m1=p1.matcher("04/30/1999");
if (m1.find()){ //you can use a while loop to get all match results
System.out.println("Month: "+m1.group(1)+" Day: "+m1.group(2)+" Year: "+m1.group(3));
}
Run Code Online (Sandbox Code Playgroud)
结果
Month: 04 Day: 30 Year: 1999
Run Code Online (Sandbox Code Playgroud)