The regex you need is
Pattern.compile("(?:\\w+=\\w*|=\\w+)(?:&(?:\\w+=\\w*|=\\w+))*");
See the regex demo. It will match:
(?:\\w+=\\w*|=\\w+)
- either 1+ word chars followed with =
and then 0+ word chars (obligatory key, optional value) or =
followed with 1+ word chars (optional key)
(?:&(?:\\w+=\\w*|=\\w+))*
- zero or more of such sequences as above.
Java demo:
String s = "one=1&two=2&=3&tr=";
Pattern patt = Pattern.compile("(?:\\w+=\\w*|=\\w+)(?:&(?:\\w+=\\w*|=\\w+))*");
Matcher m = patt.matcher(s);
if(m.matches()) {
System.out.println("true");
} else {
System.out.println("false");
}
// => true
To allow whitespaces, add \\s*
where needed. If you need to also allow non-word chars, use, say, [\\w.-]
instead of \w
to match word chars, .
and -
(keep the -
at the end of the character class).