Shahid Karimi
Shahid Karimi

Reputation: 4357

Regex to validate cookie string (Key value paired)

So far I tried this regex but no luck.

([^=;]+=[^=;]+(;(?!$)|$))+

Valid Strings:

something=value1;another=value2



something=value1 ; anothe=value2

Invalid Strings:

something=value1 ;;;name=test

some=value=3;key=val

somekey=somevalue;

Upvotes: 0

Views: 485

Answers (1)

The fourth bird
The fourth bird

Reputation: 163277

You might use an optional repeating group to get the matches.

If you don't want to cross newline boundaries, you might add \n or \r\n to the negated character class.

^[^=;\n]+=[^=;\n]+(?:;[^=;\n]+=[^=;\n]+)*$

Explanation

  • ^ Start of string
  • [^=;\n]+=[^=;\n]+ Match the key and value using a negated character class
  • (?: Non capture group
    • ;[^=;\n]+=[^=;\n]+ Match a comma followed by the same pattern
  • )* Close group and repeat 0+ times
  • $ End string

Regex demo

Upvotes: 2

Related Questions