Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match Bearer token

Tags:

regex

I'm having a bad moment trying to make a regex that can find line similar to this in files :

Bearer 89abddfb-2cff-4fda-83e6-13221f0c3d4f

It should have Bearer at the begining followed by space, and the token after is the same format : [hexadecimal, 8 char]-[hexadecimal, 4 char]-[hexadecimal, 4 char]-[hexadecimal, 4 char]-[hexadecimal, 12 char]

Any help would be very appreciated

PS: Maybe just the regex of the token format will be enough to find the token without the Bearer not sure

like image 801
Imad El Hitti Avatar asked Dec 17 '22 21:12

Imad El Hitti


2 Answers

RegEx tested with PowerShell

'Bearer\s[\d|a-f]{8}-[\d|a-f]{4}-[\d|a-f]{4}-[\d|a-f]{4}-[\d|a-f]{12}'

Edit: shorter version

'Bearer\s[\d|a-f]{8}-([\d|a-f]{4}-){3}[\d|a-f]{12}'
like image 89
TobyU Avatar answered Jan 03 '23 13:01

TobyU


import re

data = "Bearer 89abddfb-2cff-4fda-83e6-13221f0c3d4f"

print(re.findall(r'(Bearer )([a-f\d]{8})-([a-f\d]{4})-([a-f\d]{4})-([a-f\d]{4})-([a-f\d]{12})', data))

The explanation on Regex101 here.

like image 38
Andrej Kesely Avatar answered Jan 03 '23 13:01

Andrej Kesely