Why doesn't this regex match my newline separated key=value pairs?

Viewed 40

I'm trying to write a regex to validate an input that should follow these rules:

  • 0 or more lines (separated by \n, \r, or \r\n)
  • Each line is made by: from 1 to 100 a-zA-Z characters, then 1 equal sign, then from 1 to 100 alphanumerical character, then an optional newline

Examples that match:

a=1
foo=bar
a=1
b=2

(extra empty line is ok)

Examples that don't match:

a

(missing the equal sign and the value)

1=1

(key has a number)

a=1
b=

(second line missing value)

What I tried:

(?<key>[a-zA-Z]{1,100})[=](?<value>[a-zA-Z0-9]{1,100}[^\r\n|\r|\n]{1})

But this is not matching, while I expect it to:

a=one
b=two
c=3
d=33
eee=eee

The c=3 line is not matching.

See https://regex101.com/r/C039en/2/

What am I doing wrong?

Thanks!

1 Answers

Using a PCRE regex engine, you can use

^([a-zA-Z]{1,100}=[a-zA-Z0-9]{1,100})(?:\R(?1))*$

Or, if it is not PCRE compliant:

^[a-zA-Z]{1,100}=[a-zA-Z0-9]{1,100}(?:(?:\r\n?|\n)[a-zA-Z]{1,100}=[a-zA-Z0-9]{1,100})*$

See the regex demo #1 and regex demo #2.

Details #1

  • ^ - start of string
  • ([a-zA-Z]{1,100}=[a-zA-Z0-9]{1,100}) - Group 1: one to a hundred ASCII letters, =, one to a hundred ASCII alphanumeric chars
  • (?:\R(?1))* - zero or more repetitions of any line break sequence followed with Group 1 pattern
  • $ - end of string.

Details #2

  • ^ - start of string
  • [a-zA-Z]{1,100}=[a-zA-Z0-9]{1,100} - one to a hundred ASCII letters, =, one to a hundred ASCII alphanumeric chars
  • (?:(?:\r\n?|\n)[a-zA-Z]{1,100}=[a-zA-Z0-9]{1,100})* - zero or more repetitions of CRLF, CR or LF line ending, and then one to a hundred ASCII letters, =, one to a hundred ASCII alphanumeric chars
  • $ - end of string.
Related