简体   繁体   English

Java。 正则表达式。 如何解析?

[英]Java. Regular Expression. How Parse?

As input parameters I can have two types of String: 作为输入参数,我可以有两种类型的String:

codeName=SomeCodeName&codeValue=SomeCodeValue

or 要么

codeName=SomeCodeName 

without codeValue . 没有codeValue

codeName and codeValue are the keys. codeNamecodeValue是键。

How can I use regular expression to return the key's values? 如何使用正则表达式返回键的值? In this example it would return only SomeCodeName and SomeCodeValue . 在此示例中,它将仅返回SomeCodeNameSomeCodeValue

I wouldn't bother with a regex for that. 我不会为此而烦恼。 String.split with simple tokens ('&', '=') will do the job. 具有简单标记('&','=')的String.split将完成此工作。

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. 一种简单的方法是先拆分源字符串,然后针对2个部分运行2个单独的正则表达式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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