Regex to match a JSON String

后端 未结 1 1426

I am building a JSON validator from scratch, but I am quite stuck with the string part. My hope was building a regex which would match the following sequence found on JSON.o

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 16:07

    For your exact question create a character class

    # Matches any character that isn't a \ or "
    /[^\\"]/
    

    And then you can just add * on the end to get 0 or unlimited number of them or alternatively 1 or an unlimited number with +

    /[^\\"]*/
    

    or

    /[^\\"]+/
    

    Also there is this below, found at https://regex101.com/ under the library tab when searching for json

    /(?(DEFINE)
    # Note that everything is atomic, JSON does not need backtracking if it's valid
    # and this prevents catastrophic backtracking
    (?(?>\s*(?&object)\s*|\s*(?&array)\s*))
    (?(?>\{\s*(?>(?&pair)(?>\s*,\s*(?&pair))*)?\s*\}))
    (?(?>(?&STRING)\s*:\s*(?&value)))
    (?(?>\[\s*(?>(?&value)(?>\s*,\s*(?&value))*)?\s*\]))
    (?(?>true|false|null|(?&STRING)|(?&NUMBER)|(?&object)|(?&array)))
    (?(?>"(?>\\(?>["\\\/bfnrt]|u[a-fA-F0-9]{4})|[^"\\\0-\x1F\x7F]+)*"))
    (?(?>-?(?>0|[1-9][0-9]*)(?>\.[0-9]+)?(?>[eE][+-]?[0-9]+)?))
    )
    \A(?&json)\z/x
    
    
    

    This should match any valid json, you can also test it at the website above

    EDIT:

    Link to the regex

    0 讨论(0)
    提交回复
    热议问题