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 !

13
  • Escape your backslashes Commented Jun 23, 2017 at 9:49
  • By the way: Replace if A return true; else return false; with return A; Commented Jun 23, 2017 at 9:50
  • @GiladGreen Nope, his regex is good. He just needs to escape \, as it is a Java string. Commented Jun 23, 2017 at 9:53
  • See ideone.com/QjYyZG. You need "\\w+=\\w+(?:&\\w+=\\w+)*" regex. The \w+ will match 1 or more word chars, \w* would allow an empty string. Well, maybe you really want to allow =&=&=&=, no idea. Then use "\\w*=\\w*(?:&\\w*=\\w*)*". What are the requirements?. BTW, added another dupe - Validate URL query string with regex. Commented Jun 23, 2017 at 10:22
  • Regarding the update: did you really want to match the spaces before the second =? Commented Jun 23, 2017 at 10:29

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.