Home > OS >  Regex to capture ApiAuth Headers
Regex to capture ApiAuth Headers

Time:04-29

I have the following scenario sending Auth Headers to an application that can range from the following:

"APIAuth 5b6b7ed3b9708d1168455da4:hW1ZeYYLJFGBP8tEHAEGoiGD1xM="

"APIAuth-HMAC-SHA256 5b6b7ed3b9708d1168455da4:hW1ZeYYLJFGBP8tEHAEGoiGD1xM="
  

etc.

What I'd like to do is to be able to capture APIAuth and APIAuth-HMAC-SHA256 from the header leaving me the client_id:signature like so:

string = '5b6b7ed3b9708d1168455da4:hW1ZeYYLJFGBP8tEHAEGoiGD1xM='

I want to be able to grab this value from any APIAut-WHATEVER-ENCRYPTION

I've been playing around with regex's but the best I have was this /\ABearer\s /i. I thought this would have worked to grab both because the \s is more than one of any single character so I don't know why its not working. Could someone please assist? Regexs are not my strong suit. Thank you.

CodePudding user response:

For the example strings, you could match the parts that you want:

\bAPIAuth(?:-\S )?\s \K[^\s:"] :[^\s:"] 

Explanation

  • \bAPIAuth A word boundary, followed by APIAuth
  • (?:-\S )? Optionally match - and 1 non whitespace chars
  • \s \K Match 1 whitespace chars and forget what is matched so far using \K
  • [^\s:"] :[^\s:"] Match : surrounded by chars other than a whitespace char or : or " if those are also part of the string

See a rubular regex demo.

You could also match only the first part, and then replace with an empty string.

\bAPIAuth(?:-\S )?\s 

See another regex demo

  • Related