Arefe
Arefe

Reputation: 12397

Write regex for extracting info from the string

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

Answers (2)

The fourth bird
The fourth bird

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)=([^;]+);

Regex demo | Java demo

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

DevilsHnd - 退した
DevilsHnd - 退した

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

Related Questions