简体   繁体   中英

Java. Regular Expression. How Parse?

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 .

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];
}

Consider using Guava's Splitter

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM