Java:正则表达式的命名捕获组

命名捕获组格式

(?<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= "(?.*)-(?.*)-(?.*)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        // 如果没有匹配,会报错:java.lang.IllegalStateException: No match found
        if(matcher.find()){
            System.out.println("year:" + matcher.group("year"));
            System.out.println("month:" + matcher.group("month"));
            System.out.println("date:" + matcher.group("date"));
        }
    }
}

参考文章

  1. Java 正则表达式的捕获组(capture group)

你可能感兴趣的:(Java学习路线,java,正则表达式,开发语言)