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.