命名捕获组格式
(?<year>.*)-(?<month>.*)-(?<date>.*)
完整示例
package com.example.demo;import java.util.regex.Matcher;
import java.util.regex.Pattern;public class RegexTests {public static void main(String[] args) {String text = "2023-09-20";String regex= "(?<year>.*)-(?<month>.*)-(?<date>.*)";Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(text);// 如果没有匹配,会报错:java.lang.IllegalStateException: No match foundif(matcher.find()){System.out.println("year:" + matcher.group("year"));System.out.println("month:" + matcher.group("month"));System.out.println("date:" + matcher.group("date"));}}
}
参考文章
- Java 正则表达式的捕获组(capture group)