0

I have two string types:

First : key1=value1&key2=value2&key3=value3...

Second : key1=value

How can I use a Java regular expression to check whether a string is of the first or second type? Example:

String str1 = "a=1&b=2"; // true
String str2 = "a=1&"; // false
String str3 = "a=1"; // true
4
  • Are there escape characters you have to take into account? Can = be part of a value? Can & be part of a key? Commented Mar 5, 2014 at 18:17
  • 3
    Clippy says: It looks like you are trying to process GET request parameters. Would you like me to show you the normal ways of doing that rather than rolling your own? Commented Mar 5, 2014 at 18:18
  • google.com/search?q=parse+url+parameters+java Commented Mar 5, 2014 at 18:19
  • The temptation is to go for the easy rep points by posting ([^=&]+=[^=&]+&)*[^=&]+=[^=&]+ as an answer, but it's unlikely to be the best thing to do in this case. Commented Mar 5, 2014 at 18:22

1 Answer 1

1

Assuming the values are only alphanumeric characters.

String text = "a=1&b=2";
boolean match = text.matches("[a-zA-Z0-9]+=[a-zA-Z0-9]+(&[a-zA-Z0-9]+=[a-zA-Z0-9]+)*");
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.