user3809938 user3809938 - 5 months ago 12
Java Question

java pattern match regex

I have the following string:

String p = "{requestId=146bb94xxxxxR, value=false, tier=S3,ReceivedTime=0}";


I want to extract the request Id value, so want my output to be

146bb94xxxxxR


Here is what I tried

Pattern MY_PATTERN = Pattern.compile("\\requestId=(.*?)\\,");
Matcher m = MY_PATTERN.matcher(p);
while (m.find()) {
String s = m.group(1); // s now contains "BAR"
}


However i get no output, there is a problem with the regex, but I am not sure how to correct it.

Answer
Pattern.compile("requestId=(.*?),");

You should delete redundant characters escape (\\, and \\r (it means the carriage-return character)) and it will work fine.