otc otc - 3 years ago 197
Java Question

Ignore parameters in url using regex in java

So I have the following route /path1/path2/{value1}/path3/{value2} and I'm trying to figure out if the request route matches path1 path2 and path3 regardless the {value1} and {value2} which change.

This is what I have but its not matching:

@Test
public void testURLMatches() {
String input = "/path1/path2/123/path3/456";
Pattern pattern = Pattern.compile("\\/path1\\/path2\\/([a-zA-Z0-9]{0,})\\/path3\\/([a-zA-Z0-9]{0,})");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Does match!");
} else {
System.out.println("Does not match!");
}
assertTrue(matcher.find());
}


Edit 1:
Added in the pattern \/ which was missing originally

Answer Source

I think the Regex you are looking at is

^\/path1\/path2\/([\w]+)\/path3\/([\w]+)$

PS : You have another problem in your test, you call the matcher.find() functions twice, whereas you should only call it once. Remove the if condition.

In Java, you get

@Test
public void testURLMatches() {
    String input = "/path1/path2/123/path3/456";
    Pattern pattern = Pattern.compile("^\\/path1\\/path2\\/([\\w]+)\\/path3\\/([\\w]+)$");
    Matcher matcher = pattern.matcher(input);
    assertTrue(matcher.find());
}

(example)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download