有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

理解Java正则表达式模式示例

我有一个Java正则表达式示例,可以根据给定的模式从给定的输入字符串中提取内容:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternEx {
    static Pattern PATTERN_ONE = Pattern.compile("^(/?test/[^/]+)/([^/]+)(/?.*)$");
    static Pattern PATTERN_TWO = Pattern.compile("^(/?test)/([^/]+)(/?.*)$");
    static Pattern[] PATTERNS = { PATTERN_ONE, PATTERN_TWO };

    public static void main(String[] args) {
        for (Pattern p : PATTERNS) {
            Matcher m = p.matcher("/test/hello/world/checking/");
            if (m.matches()) {
                System.out.println(m.group(2));
            }
        }
    }
}

该程序的输出为:

world
hello

我已经浏览了Java doc for regular expressions,根据文档,我可以看到这里的模式使用了“Capturing Groups

但我无法理解我的示例中的模式是如何工作的,它的含义是什么,以及它如何能够从输入字符串中提取数据。有人能帮我理解这个代码吗


共 (1) 个答案

  1. # 1 楼答案

    希望这有助于:

    模式1:^(/?test/[^/]+)/([^/]+)(/?.*)$

    group 1: (/?test/[^/]+) = "/test/hello"
    group 2: ([^/]+) = "world"
    group 3: (/?.*) = "/checking/"
    

    模式2:^(/?test)/([^/]+)(/?.*)$

    group 1: (/?test) = "/test"
    group 2: ([^/]+) = "hello"
    group 3: (/?.*) = "world/checking/"
    

    提示:

    /?test - the slash is optional = "test", "/test"
    [^/] - anything else than a slash = "hello", "world", "$#* abc",...
    [^/]+ - the plus stands for 1 or more times = "a", "aa",...
    /?.* - optional slash and any character 0 or more times = "","/","a","/a",...
    

    ^,$,?,,*,[]-regex操作员,你可以用谷歌搜索他们的意思