Search code examples
regex

Regex to match JWT


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


Solution

  • If you are working with an HTML document as a string and you are using Javascript to run your regular expression, you could do something like the following:

    const html = '<div>stuff</div>something "contextJwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJIZWxsbyB5b3UiLCJuYW1lIjoiV2h5IGFyZSB5b3UgY2hlY2tpbmcgbXkgdG9rZW4_ICggzaHCsCDNnMqWIM2hwrApIiwiaWF0IjoxNTE2MjM5MDIyfQ.yAP0xiTwp6vqIYbLKLVBRv-gTyMvU17rT3H8uErLjHA" <div> other stuff</div>';
    var regex = /"contextJwt":\s*"(.*)"/;
    console.log(html.match(regex)[1]);
    
    /* yields the encoded JWT string:
     eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJIZWxsbyB5b3UiLCJuYW1lIjoiV2h5IGFyZSB5b3UgY2hlY2tpbmcgbXkgdG9rZW4_ICggzaHCsCDNnMqWIM2hwrApIiwiaWF0IjoxNTE2MjM5MDIyfQ.yAP0xiTwp6vqIYbLKLVBRv-gTyMvU17rT3H8uErLjHA
    
    */
    

    You can tighten up your match from the simple (.*) to the specific characters that are allowed in a valid encoded JWT (per Helio Santo's answer), but since regexes are finicky, I usually start with the simplest solution and only tighten it down when necessary.

    What you do with the string that represents an encoded JWT is perhaps another question entirely.