1

As input parameters I can have two types of String:

codeName=SomeCodeName&codeValue=SomeCodeValue

or

codeName=SomeCodeName 

without codeValue.

codeName and codeValue are the keys.

How can I use regular expression to return the key's values? In this example it would return only SomeCodeName and SomeCodeValue.

1
  • would your SomeCodeName and SomeCodeValue may contain & or = ? Commented Nov 18, 2011 at 1:53

3 Answers 3

5

I wouldn't bother with a regex for that. String.split with simple tokens ('&', '=') will do the job.

String[] args = inputParams.split("&");
for (String arg: args) {
    String[] split = arg.split("=");
    String name = split[0];
    String value = split[1];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Check out Guava's Splitter.MapSplitter
+1, but I think you should change arg.split("=") to arg.split("=", 2), since equals-signs are allowed in the values of query-string parameters.
Note that Argument to String.split is a regex
You might need to consider using Pattern as new pattern gets created in every iteration when arg.split("=") is used
3

Consider using Guava's Splitter

String myinput = "...";
Map<String, String> mappedValues = 
           Splitter.on("&")
                   .withKeyValueSeparator("=")
                   .split(myinput);

Comments

1

The simple way is to split the source string first and then to run 2 separate regular expressions against 2 parts.

Pattern pCodeName = Pattern.compile("codeName=(.*)");
Pattern pCodeValue = Pattern.compile("codeValue=(.*)");

String[] parts = str.split("\\&");
Matcher m = pCodeName.matcher(parts[0]);
String codeName = m.find() ? m.group(1) : null;

String codeValue = null;
if (parts.length > 1) {
    m = pCodeValue.matcher(parts[1]);
    codeValue = m.find() ? m.group(1) : null;
}

}

But if you want you can also say:

Pattern p = Pattern.compile("codeName=(\\w+)(\\&codeValue=(\\w+))?");
Matcher m = p.matcher(str);

String codeName = null;
String codeValue = null;

if (m.find()) {
    codeName = m.group(1);
    codeValue = m.groupCount() > 1 ? m.group(2) : null;
}

1 Comment

IMO Second option is better as it would be a stricter match

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.