How to write ant path pattern except one path?

Viewed 543

Spring Framework has the AntPathMatcher which is borrowed from Ant.

I have the following path:

  • /api/index
  • /api/test/random
  • /api/test/another
  • /api/other/1
  • /api/other/2

and I will add more paths like /api/other/other, I'd like to ask how can I create an AntPath Pattern to match all path except the /api/index.

I have tried to make some tests, but none of the following works.

  private static final String PATTERN = "/api/*/**";

  @Test
  public void test() {
    AntPathMatcher pathMatcher = new AntPathMatcher();
    boolean match = pathMatcher.match(PATTERN, "/api/index");
    System.out.println(match);
    match = pathMatcher.match(PATTERN, "/api/test/test");
    System.out.println(match);
  }
1 Answers

As stated in the Spring AntPathMatcher Docu you can add a path variable to your pattern where you can specify a Regex this path variable has to match:

    String PATTERN = "/api/{path:^(?!(index)$).*$}/**";

The above pattern for the path variable accepts any characters but the string "index". If you want to filter out any strings containing the substring "index" you could change it to:

    String PATTERN = "/api/{path:^(?!(index)).*$}/**";


    AntPathMatcher pathMatcher = new AntPathMatcher();
    boolean match = pathMatcher.match(PATTERN, "/api/index");
    assert match == false;
    match = pathMatcher.match(PATTERN, "/api/index/sec");
    assert match == false;
    match = pathMatcher.match(PATTERN, "/api/index4");
    assert match == false;
    match = pathMatcher.match(PATTERN, "/api/test/random");
    assert match == true;
    match = pathMatcher.match(PATTERN, "/api/test/another");
    assert match == true;
    match = pathMatcher.match(PATTERN, "/api/other/1");
    assert match == true;
    match = pathMatcher.match(PATTERN, "/api/other/2");
    assert match == true;
    match = pathMatcher.match(PATTERN, "/api/other/index");
    assert match == true;
Related