Joseph Cox
Joseph Cox

Reputation: 37

Java Regex Group By Doesn't Work As Expected For Numbers

I am running into an issue with Java Matchers. I may be overlooking something very small here but the following matcher does not give the expected results

    private static final Pattern STANDARD_NAME_PATTERN = Pattern.compile("MySampleString.*?/(?<PatternOne>.+?)/(?<PatternTwo>\\w+?)/PatternThree(?<PatternThree>\\d+?).*");

    public static void main(String[] args) {
        String key = "PatternThree";
        String value = "EMPTY";
        String name = "MySampleString/IRRELEVANT/IRRELEVANT/PatternThree15";
        Matcher matcher = STANDARD_NAME_PATTERN.matcher(name);
        if (matcher.matches()) {
            value = matcher.group(key);
        }
        System.out.println(value);
    }

The following output is

1

However, I would expect it to be 15 here since we are matching the numbers with \d+ The other two patterns are matching with words... Not sure what the issue is here, if someone could provide insight.

One of the hacks I could use is

Pattern.compile("MySampleString.*?/(?<PatternOne>.+?)/(?<PatternTwo>\\w+?)/PatternThree(?<PatternThree>\\d\\d\\d?).*");

But ideally would not want to do this since it doesn't scale

Upvotes: 0

Views: 43

Answers (1)

Alireza
Alireza

Reputation: 2123

Try this (remove last question mark):

MySampleString.*?/(?<PatternOne>.+?)/(?<PatternTwo>\w+?)/PatternThree(?<PatternThree>\d+).*

See Regex Demo

Upvotes: 2

Related Questions