簡體   English   中英

了解Java regex模式示例

[英]Understanding the Java regex pattern example

我有一個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文檔中的正則表達式,並且基於該文檔,我可以看到這里的模式使用的是“ 捕獲組

但是我無法理解示例中的模式如何工作,其含義是什么以及如何從輸入字符串中提取數據。 有人可以幫助我理解此代碼。

希望這可以幫助:

模式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",...

^,$,?,。,*,[]-正則表達式運算符,您可以搜索它們的含義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM