Learner
Learner

Reputation: 21393

Understanding the Java regex pattern example

I have a Java regular expressions example that works and extract content from given input string based on the given pattern:

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));
            }
        }
    }
}

The output of this program is:

world
hello

I have gone through the Java doc for regular expressions and based on the document I can see that the pattern here is using "Capturing Groups"

But I am not able to understand how the pattern in my example works, what is its meaning and how it is able to extract data from input string. Can someone please help me in understanding this code.

Upvotes: 1

Views: 1962

Answers (1)

TomasZ.
TomasZ.

Reputation: 469

Hope this helps:

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

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

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

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

Hints:

/?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 operators, you can google their meaning.

Upvotes: 2

Related Questions