Moon
Moon

Reputation: 22565

How to get matched string in Java?

Um..I'm not a java developer, but I'm editing a java plugin.

So.. basically, this plugin matches ^(/$)|(/cn/(.*)+$) pattern and redirect to a user.

The following is code snippet from the plugin.

if(uriPattern != null) {
    Pattern pattern = Pattern.compile(uriPattern); 
    Matcher matcher = pattern.matcher(request.getRequestURI());
    matcher.find();
    matchURI = matcher.matches();


}

if (matchURI && redirectTool.shouldRedirectRequest()) {
    //do something
}

as you see, the pattern matches either / or /cn/[EVERYTHING] url. How do I get empty string when / is matched and cn when /cn/[EVERYTHING] is matched?

I tried matcher.group(), matcher.start(), and matcher.end()...

Upvotes: 0

Views: 4728

Answers (1)

9000
9000

Reputation: 40894

matcher.group(1) is / when your first subpattern matches, matcher.group(2) is /cn/whatever when your second subpattern matches.

And you don't seem to need the + and nested parens. I'd write your expression simpler: ^(/$)|(/cn/.*$)

Upvotes: 1

Related Questions