Match regex "labes" key/value pair

I try to write a regex rule that matches "labels" which are basically key=value pairs.
In key & value should only be alphanumeric values (and -) be allowed.

Thats what i have tried so far:/(-*.)=(-*.)/g
But it does not work with the input patter a-b=c-d, it does not match the "a" & "-d"

Valid input patterns:

a=b
1=1
a-b=c-d
a=b-c

Invalid input:

 foo=bar
ba=r=b=az
b = z
a-b=c - d
te:st=st:ring

Notice the white space. White space in either key or value are invalid and only one = is allowed.

I created a example on: https://regex101.com/r/GNm5K7/1

>Solution :

You could write the pattern matching 1 or more alphanumerics or - in a character class using [a-zA-Z0-9-]+

^[a-zA-Z0-9-]+=[a-zA-Z0-9-]+$

See a regex101 demo.

If the - can not be at the start or at the end:

^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*=[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$

See another regex101 demo.

Leave a Reply