美文网首页
Java 正则表达式之分组

Java 正则表达式之分组

作者: Tinyspot | 来源:发表于2023-10-25 12:26 被阅读0次

    1. 分组

    • 分组由小括号组成,一个小括号是一组
    • 多层嵌套:左小括号开始,第一个左括号是第一组,第二个是第二组
    # 不加小括号
    regex = "\\d{3,5}[a-z]{2}"
    # 加小括号
    regex = "(\\d{3,5})([a-z]{2})"
    

    2. group

    2.1 group()

    group() 等价 group(0)

    public String group() {
        return group(0);
    }
    

    Matcher.group(0) 表示正则表达式中符合条件的字符串
    Matcher.group(1) 表示正则表达式中符合条件的字符串中的第一个()中的字符串

    public class RegexGroupDemo {
    
        public static void print(Object o) {
            System.out.println(o);
        }
    
        @Test
        public void digitMix() {
            Pattern pattern = Pattern.compile("(\\d{3,5})([a-z]{2})");
            Matcher matcher = pattern.matcher("123aa-12345bb-3434cc-55");
    
            while (matcher.find()) {
                print("group(): " + matcher.group());
                print(matcher.group(1) + "###" + matcher.group(2));
            }
        }
    
        @Test
        public void digitMix2() {
            Pattern pattern = Pattern.compile("\\d{3,5}[a-z]{2}");
            Matcher matcher = pattern.matcher("123a-12345bb-3434cc-55");
            while (matcher.find()) {
                print("group(): " + matcher.group());
            }
        }
    }
    

    2.2 group(int group)

    private static final String GROUP_REGEX = "(name\\d+).*(code\\d+)";
    private static final Pattern groupCompile = Pattern.compile(GROUP_REGEX);
    @Test
    public void groupMatch() {
        String data = "name123,code001,234code222,333code111,2323";
        Matcher groupMather = groupCompile.matcher(data);
        System.out.println(groupMather.groupCount());
    
        while(groupMather.find()) {
            print("group: " + groupMather.group());
    
            for (int i = 1; i <= groupMather.groupCount(); i++) {
                print("group" + i + ": " + groupMather.group(i));
            }
        }
    }
    

    3. 分组引用替换 ($)

    示例:超过10个数字,改为字符串

    @Test
    public void test() {
        /**
         * {
         *     "1001": [
         *         "id": 1234567890123,
         *         "itemId": 123456789
         *     ],
         *     "1002": [
         *         "id": 12345,
         *         "itemId": 1234567890123
         *     ]
         * }
         */
        String jsonStr = "{\"1001\":[\"id\":1234567890123,\"itemId\":123456789],\"1002\":[\"id\":12345,\"itemId\":1234567890123]}";
    
        String result1 = jsonStr.replaceAll("(\\d{10,})", "\"$1\"");
        // result1: {"1001":["id":"1234567890123","itemId":123456789],"1002":["id":12345,"itemId":"1234567890123"]}
    
        String result2 = jsonStr.replaceAll("\"itemId\":(\\d{10,})", "\"itemId\":\"$1\"");
        // result2: {"1001":["id":1234567890123,"itemId":123456789],"1002":["id":12345,"itemId":"1234567890123"]}
    
    }
    

    相关文章

      网友评论

          本文标题:Java 正则表达式之分组

          本文链接:https://www.haomeiwen.com/subject/bwyeidtx.html