I'm learning about regex and attempting to extract from this string:
"a,b,c,test1=0 test2=1 test3=2 test4=3 Request t=4,test6_r_a=5,d,e,f"
the key/values:
test1=0
test2=1
test3=2
test4=3
Request t=4
test6_r_a=5
I use this regex :
"\\p{Alnum}+ *=(?: *\\p{Alnum}+)+ "
which produces :
test1=0
test2=1
test3=2
test4=3 test5 Request
The key,value pairs : Request t=4,test6_r_a=5 are not matched.
What modification of regex is required to match the expected values ?
src :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractMatch {
public static void main(String args[]) {
final String text = "a,b,c,test1=0 test2=1 test3=2 test4=3 test5 Request t=4,test6_r_a=5,d,e,f";
final Pattern pattern = Pattern.compile("\\p{Alnum}+ *=(?: *\\p{Alnum}+)+ ");
final Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
I'm attempting to allow the scenario where variable number of spaces can be within key, for example "Request t" or "Request t d"
update :
The string to be parsed is :
"a,b,c,test1=0 test2=1 test3=2 test4=3 t Request=4,test6_r_a=5,d,e,f"
I've updated regex posted in answer by anubhava to use
"\\w+=\\w+(?:\\h+\\d+)*\\b(?!=)"
instead of :
"\\w+=\\w+(?:\\h+\\w+)*\\b(?!=)"
which produces :
test1=0
test2=1
test3=2
test4=3
Request=4
test6_r_a=5
But I'm expecting :
test1=0
test2=1
test3=2
test4=3
t Request=4
test6_r_a=5
src :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractMatch {
public static void main(String args[]) {
final String text = "a,b,c,test1=0 test2=1 test3=2 test4=3 t Request=4,test6_r_a=5,d,e,f";
final Pattern pattern = Pattern.compile("\\w+=\\w+(?:\\h+\\d+)*\\b(?!=)");
final Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}