Reputation: 12397
I have a String provided below:
AWSALB=eIFPQSLLQjg+; Expires=Fri, 20 Mar 2020 03:16:01 GMT; Path=/, AWSALBCORS=eIFPQSLLQjg+vW+; Expires=Fri, 20 Mar 2020 03:16:01 GMT; Path=/; SameSite=None; Secure, SilverWebAuth=48199A; expires=Fri, 13-Mar-2020 04:01:01 GMT; path=/; HttpOnly
I want to capture only the specific info provided below:
AWSALB=eIFPQSLLQjg+; AWSALBCORS=eIFPQSLLQjg+vW+; SilverWebAuth=48199A;
I have the regex of (\AWSALB=(.*?)\;) but this only captures the first term. I would like to have the other 2 terms as well. How do I write a regex for the purpose?
Upvotes: 1
Views: 80
Reputation: 163217
You could use an alternation with an optional part for CORS
and use a negated character class matching any char other than ;
for the value.
Then you could get the whole match using .group(0)
or get the value only using .group(1)
(?:AWSALB(?:CORS)?|SilverWebAuth)=([^;]+);
For example
String regex = "(?:AWSALB(?:CORS)?|SilverWebAuth)=([^;]+);";
String string = "AWSALB=eIFPQSLLQjg+; Expires=Fri, 20 Mar 2020 03:16:01 GMT; Path=/, AWSALBCORS=eIFPQSLLQjg+vW+; Expires=Fri, 20 Mar 2020 03:16:01 GMT; Path=/; SameSite=None; Secure, SilverWebAuth=48199A; expires=Fri, 13-Mar-2020 04:01:01 GMT; path=/; HttpOnly\n";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println("");
}
Output
AWSALB=eIFPQSLLQjg+;
eIFPQSLLQjg+
AWSALBCORS=eIFPQSLLQjg+vW+;
eIFPQSLLQjg+vW+
SilverWebAuth=48199A;
48199A
Upvotes: 1
Reputation: 9192
It would go something like this:
String a = "AWSALB=eIFPQSLLQjg+; Expires=Fri, 20 Mar 2020 03:16:01 GMT; "
+ "Path=/, AWSALBCORS=eIFPQSLLQjg+vW+; Expires=Fri, 20 Mar 2020 "
+ "03:16:01 GMT; Path=/; SameSite=None; Secure, SilverWebAuth=48199A; "
+ "expires=Fri, 13-Mar-2020 04:01:01 GMT; path=/; HttpOnly";
String regex = "AWSALB=(.*?);|AWSALBCORS=(.*?);|SilverWebAuth=(.*?);";
Pattern p = Pattern.compile(regex); // the pattern to search for
Matcher m = p.matcher(a);
StringBuilder sb = new StringBuilder("");
while(m.find()) {
if (!sb.toString().equals("")) {
sb.append(" ");
}
sb.append(m.group(0));
}
System.out.println(sb.toString());
Output to Console:
AWSALB=eIFPQSLLQjg+; AWSALBCORS=eIFPQSLLQjg+vW+; SilverWebAuth=48199A;
Upvotes: 1