I have 2 URI Patterns with their regex:
1. "/api/orders/{id}/{version}" -> "^/api/orders/. /. $"
2. "/api/orders/{id}" -> "^/api/orders/. $"
But with the above regex, String /api/orders/123-blah$-789/v1
matches both the regex patterns 1 and 2.
What regex can I use so that the above string matches only pattern 1's regex and not 2?
(The path may or may not be URL Encoded)
CodePudding user response:
You could keep your first regex (^/api/orders/. /. $
) and replace the second one with this:
^\/api\/orders\/[[\p{Alnum}\p{Punct}]&&[^\/]] $
Basically, you accept every symbol or alphanum character following orders/
unless there is a slash in there. Like so, you're guaranteed that orders/
will be followed only by a single subpath.
Here is a link to test the regex:
https://regex101.com/r/KMEeXX/2
CodePudding user response:
You can restrict both pattern by using a negated character class [^/]
matching 1 characters excluding a forward slash.
For the first pattern you can use:
^/api/orders/[^/] /[^/] $
For the second pattern you can use
^/api/orders/[^/] $
CodePudding user response:
This might seem a little hardcoded but gets the job done.
And personally I prefer regex to be very specific.
Pattern p = Pattern.compile("^/api/orders/. /. $");
Pattern q = Pattern.compile("^/api/orders/[^/] $");
System.out.println(p.matcher("/api/orders/123-456-789/v1").matches());
System.out.println(q.matcher("/api/orders/123-456-789/v1").matches());
System.out.println(p.matcher("/api/orders/123-456-789").matches());
System.out.println(q.matcher("/api/orders/123-456-789").matches());