jucas jucas - 6 months ago 14
Java Question

How to test if a URL contains certain parameters but not others using regex

I have an url in this format:

http://www.example.com/path?param1=value1&param2=value2

I need a regex to match the path and params1 and params2 in any order but if param3 is present then I need it to fail so:

String str1 = "/path?param1=value1&param2=value2"; // This will match
String str2 = "/path?param2=value2&param1=value1"; // This will match
String str3 = "/path?param1=value1&param2=value&param3=value3"; // This will not match


So for I've tried using lookarounds to match the parameters but it is failing:

/path\?(?!param3)(?=param1=.*)(?=param2=.*)


Any thoughts?

P.D. For the curious I'm trying to match a specific URL from an AndroidManifest.xml file https://developer.android.com/guide/topics/manifest/data-element.html

Answer

Try this one out:

^(?!.*param3)(?=.*param1=)(?=.*param2=).*$

https://regex101.com/r/rI1lH5/1

If you want the path in as well, then

^\/path(?!.*param3)(?=.*param1=)(?=.*param2=).*$