Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match JWT

Tags:

regex

I don't have experience with Regex and I'm asking for your help.

I need a regex to capture the JWT inside the following string:

"contextJwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJIZWxsbyB5b3UiLCJuYW1lIjoiV2h5IGFyZSB5b3UgY2hlY2tpbmcgbXkgdG9rZW4_ICggzaHCsCDNnMqWIM2hwrApIiwiaWF0IjoxNTE2MjM5MDIyfQ.yAP0xiTwp6vqIYbLKLVBRv-gTyMvU17rT3H8uErLjHA"

Request answer (2363 lines)

Thanks for your time

like image 617
Grampet Avatar asked Jan 20 '26 13:01

Grampet


2 Answers

I created a regex which might not be the most elegant but it appears to works.

(^[A-Za-z0-9-_]*\.[A-Za-z0-9-_]*\.[A-Za-z0-9-_]*$)

A more concise version could be also:

(^[\w-]*\.[\w-]*\.[\w-]*$)

However, I believe that also non-latin characters would be allowed which would be disallowed as JWT.

like image 128
Alex_P Avatar answered Jan 23 '26 07:01

Alex_P


I'm answering late as this is still one of the top answers on google for jwt regex and as is often the case, the accepted answers aren't entirely correct.

The minimum encoded base64url output is two characters, so if you want to avoid matching strings like a.a.a (which isn't a JWT) then the following regex is a better alternative:

^[A-Za-z0-9_-]{2,}(?:\.[A-Za-z0-9_-]{2,}){2}$
like image 36
Buffoonism Avatar answered Jan 23 '26 07:01

Buffoonism



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!