3

I am trying to verify if the string match a regular expression or not. The URL format is : key=value&key=value&....

Key or value can be empty.

My code is :

Pattern patt = Pattern.compile("\\w*=\\w*&(\\w *=\\w*)* ");
Matcher m = patt.matcher(s);
if(m.matches()) return true;
else return false;

when i enter one=1&two=2, it shows false whereas it should show true. Any idea !

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Amir Choubani
  • 829
  • 2
  • 14
  • 28

1 Answers1

4

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).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563