I have a string in this format(response from EBS Payment Gateway)
key1=value1&key2=value2&key3=value3
How to bind to this class object without using split method?
public class MyClass {
private String key1;
private String key2;
private String key3;
// getter and setter methods
...
}
Try following
public class MyClass {
private String key1;
private String key2;
private String key2;
public MyClass(String k1,String k2,String k3)
{
Key1 = k1;
Key2 = k2;
Key3 = k3;
}
// getter and setter methods
...
}
And while creating object of class
String response = "key1=value1&key2=value2&key3=value3";
String[] keys = response.split("&");
MyClass m = new MyClass(keys[0].split("=")[1],keys[1].split("=")[1],keys[2].split("=")[1])
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
}
Output:
key1
key2
key3
Of course, this can be shortened to:
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
}
Breakdown:
"&?([^&]+)=";
&?
: says 0 or 1 &
[^&]+
matches 1 or more characters not equal to &
([^&]+)
captures the above characters (allows you to extract them)&?([^&]+)=
captures the above characters such that they begin with 0 or 1 &
and end with =
NB: Even though we did not exclude =
in [^&]
, this expression works because if it could match anything with an =
sign in it, that string would also have an '&' in it, so [^&=]
is unnecessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With