我有这种格式的字符串(来自EBS Payment Gateway的回复)
key1=value1&key2=value2&key3=value3
如何不使用split方法绑定到此类对象?
public class MyClass {
private String key1;
private String key2;
private String key3;
// getter and setter methods
...
}
String template = "key1=value1&key2=value2&key3=value3";
String pattern = "&?([^&]+)=";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(template);
while (m.find())
{
System.out.println(m.group(1)); //prints capture group number 1
}
输出:
key1
key2
key3
当然,可以将其缩短为:
Matcher m = Pattern.compile("&?([^&]+)=").matcher("key1=value1&key2=value2&key3=value3");
while (m.find())
{
System.out.println(m.group(1)); //prints capture group number 1
}
分解:
"&?([^&]+)=";
&?
:表示0或1&
[^&]+
匹配1个或多个不等于等于&
([^&]+)
捕获上述字符的字符(允许您提取它们)
&?([^&]+)=
捕获上述字符,使得它们以0或1开头&
并以结尾=
注意:即使我们没有排除=
in [^&]
,该表达式仍然有效,因为如果它可以匹配带有=
符号的任何内容,那么该字符串中也将带有'&',因此[^&=]
是不必要的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句