Reputation: 5170
I am trying to match particular part of the URI only when it is not followed by anything, or when it followed by '?'.
.../survey?expand=all //should match
.../survey //should match
.../survey/.. //should not match
I could not find a way to do that in one pattern. I tried (?=.*survey(?!\\?))
and did not work. I also could not find a way to do it in two separate patterns. For example, I want to match .../survey
and not .../survey/...
but this .*?/survey\\b
did not work for me.
My parser:
public class UriParser { private static String reqUriPath = null; private static String pattern = null; public static Boolean isURIMatching(Object routePattern, String pattern){ reqUriPath = routePattern.toString(); return checkPattern(reqUriPath, pattern); } private static Boolean checkPattern(String reqUriPath, String pattern) { Pattern p = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(reqUriPath); return m.find(); } }
Upvotes: 0
Views: 765
Reputation: 5789
I have updated my regex with better answer
\\/survey(?(?=\\?)\\S*|$)
Explanation:
Here (?(?=\\?)\\S*|$)
is basically an If clause i.e. (?=\\?) --> if(contains ?)
else |$ so we have following condition :-
1. ?=<condition>
i.e. \\? --> ?
i.e. literal ? , so if ? is found in the String then allow \S* any nonwhite space.
2. |
is Else condition i.e. else the string must end there, hence no chance of matching / any further.
If you feel confused with the explanation you can check out below link for regex 101 which has a coll explanation about the regex with all the description
https://regex101.com/r/WCt3WB/2
Upvotes: 1
Reputation: 2195
I am trying to match particular part of the URI only when it is not followed by anything, or when it followed by '?'.
You can do this without Regex;
public class UriParser {
public static void main(String []args){
System.out.println(isURIMatching("http://test.com/survey?expand=all", "survey"));
System.out.println(isURIMatching("http://test.com/survey", "survey"));
System.out.println(isURIMatching("http://test.com/survey/anything", "survey"));
}
public static Boolean isURIMatching(Object routePattern, String pattern){
final String reqUriPath = routePattern.toString();
final int lastIndex = reqUriPath.lastIndexOf(pattern);
final String lastPart = reqUriPath.substring(lastIndex+pattern.length()).trim();
return "".equals(lastPart) || lastPart.startsWith("?");
}
}
Upvotes: 0