Home > OS >  How to extract key-value data from a string containing multiple cookies?
How to extract key-value data from a string containing multiple cookies?

Time:04-27

Does anyone have an idea for a regex that can match multiple cookies (name, value pairs, combined by '=' and separated by '; ') in a string. With my design I can only match one cookie so far.

^(?<cookie>(?<name>. [^;])=(?<value>.*[^;])(;\s*)?) $

I would like to respect all special characters that cookies can contain. I'd like to use a regex and not rely on split and other functions provided by js.

Thank you very much,

Cheers!

CodePudding user response:

I slightly tweaked you regex to this: /(?<cookie>(?<name>[^=] )=(?<value>[^;] );\s*)/gm

For a test string: "name1=value1;name2=value2;"
This produces the matches:

match1: name1=value1;
cookie: name1=value1;
name: name1
value: value1

match2: name2=value2;
cookie: name2=value2;
name: name2
value: value2

Test here: https://regex101.com/r/CNZqnj/2

EDIT:
Made changes according to user 'The Fourth Bird's suggestions in the comment.

  • Related