Home > Blockchain >  Regex match multiple lines from an AWS Credentials file
Regex match multiple lines from an AWS Credentials file

Time:03-26

Given the following text to match, how do I get the first aws_session_expiration value after [apple] (ie 2022-03-26T09:28:28 0000):

[apple]
aws_access_key_id = test
aws_secret_access_key = test
aws_session_expiration = 2022-03-26T09:28:28 0000

[orange]
aws_access_key_id = test
aws_secret_access_key = test
aws_session_expiration = 2022-01-20T01:01:00 0000

I've tried the following, but I can't stop the matching where I need to.

(apple)((.|\n)*)(?<=aws_session_expiration).

CodePudding user response:

I came up with the following:

(?<=\[apple\])(.*\s)*?aws_session_expiration\ =\ (?<expire>(\d -) \d T(\d :) \d*\ \d )

You can get the value from the expire capture group.

Explanation:

(?<=\[apple\])(.*\s)*?aws_session_expiration\ =\ (?<expire>(\d -) \d T(\d :) \d*\ \d )
(?<=         )                                                                          #positive lookbehind
    \      \                                \  \                                \       #escape special characters to be treated as text
     [apple]                                                                            #text for lookbehind
              (    )*?                                                                  #match group between 0 and infinity, non greedy
               .*\s                                                                     #any character between 0 and infinity, followed by a whitespace
                      aws_session_expiration =                                          #literal text to match
                                                 (?<expire>                          )  #capture group called "expire"
                                                            (\d -) \d T(\d :) \d*\ \d ) #match date and time in the specified format
                                                            
  • Related