Home > Net >  Regex for KeyValue pattern
Regex for KeyValue pattern

Time:02-01

I have to check if a string follows the following patterns:

Field1=value1
Field1=value1,Field2=value2
7645a=fds23,Field2=dsd$

The words 'field1', 'value1' don't count, the important thing is that it has to be something=something and if there is more than 1, it should be a comma for each pair.

I reached the following regex:

((\w )[^=])=((\w )[^=])

"Match any one or more word except if it has =, then there should be an = and then match any one or more word except if it has =".

The thing is, it does take the comma but I think is because of \w. I don't think this is correct.

I'm using https://regexr.com/ to check for the correct regular expression.

CodePudding user response:

If you need to match symbols like $, then don't use \w. This satisfies all your conditions:

(?:([^,=\n] )=([^,=\n] ))(?:,([^,=\n] )=([^,=\n] ))*

Explanation:

(?:                  // Begin non-capturing group (first key=value pair)
    (                // Begin capturing group (key)
        [^,=\n]      // Match one or more characters that aren't comma, equals, or new line
    )                // End capturing group (key)
    =                // Equals
    (                // Begin capturing group (value)
        [^,=\n]      // Match one or more characters that aren't comma, equals, or new line
    )                // End capturing group (value)
)                    // End non-capturing group (first key=value pair)
(?:                  // Begin non-capturing group (additional key=value pairs)
    ,                // Starts with comma (otherwise entire group fails)
    (                // Begin capturing group (key)
        [^,=\n]      // Match one or more characters that aren't comma, equals, or new line
    )                // End capturing group (key)
    =                // Equals
    (                // Begin capturing group (value)
        [^,=\n]      // Match one or more characters that aren't comma, equals, or new line
    )                // End capturing group (value)
)                    // End non-capturing group (additional key=value pairs)
*                    // Match 0 or more of the additional key value pairs

Test Here

  •  Tags:  
  • Related