Regular expression for parsing name value pairs

后端 未结 3 2030
再見小時候
再見小時候 2020-11-28 09:14

Can someone provide a regular expression for parsing name/value pairs from a string? The pairs are separated by commas, and the value can optionally be enclosed in quotes.

3条回答
  •  死守一世寂寞
    2020-11-28 09:23

    This is how I would do it if you can use Perl 5.10.

    qr/
      (?
        (?:
          [^=,\\]
        |
          (?&escape)
        )++ # Prevent null keys
      )
    
      \s*+
      =
      \s*+
    
      (?
        (?"ed)
      |
        (?:
          [^=,\s\\]
        |
          (?&escape)
        )++ # Prevent null value ( use quotes for that )
      )
    
      (?(DEFINE)
        (?\\.)
        (?
          "
            (?:
              (?&escaped)
            |
              [^"\\]
            )*+
          "
        )
      )
    /x
    

    The elements would be accessed through %+.

    perlretut was very helpful in creating this answer.

提交回复
热议问题