Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression java for URL parameter string

Tags:

java

regex

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 !

like image 875
Amir Choubani Avatar asked Nov 24 '25 07:11

Amir Choubani


1 Answers

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

like image 147
Wiktor Stribiżew Avatar answered Nov 26 '25 23:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!