Skip to content

Instantly share code, notes, and snippets.

@dolmen
Last active August 20, 2017 17:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dolmen/4500712 to your computer and use it in GitHub Desktop.
Save dolmen/4500712 to your computer and use it in GitHub Desktop.
use 5.012;
#
# Regexp for a unicode string JSON
# (the BOM and decoding must have been processed before)
# This means that with PCRE (used for example in PHP), the input must
# have been converted to UTF-8 and the '/u' flag must be given
#
my $json_regex =
qr/
(?(DEFINE)
(?<spaces> [ \t\r\n]* )
(?<literal> true | false | null )
(?<number> -? (?: 0 | [1-9][0-9]* ) (?: \. [0-9]+ )? (?: [eE] [+-]? [0-9]+ )? )
(?<string> " (?: [\x20-\x21\x23-\x5B\x5D-\x{10FFFF}]+ | \\ (?: ["\\bfnrt\/] | u [0-9a-f]{4} ) )* " )
(?<array> \[ (?: (?&value) (?: , (?&value) )* )? \] )
(?<pair> (?&spaces) (?&string) (?&spaces) : (?&value) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \} )
(?<value> (?&spaces) (?: (?&number) | (?&literal) | (?&string) | (?&array) | (?&object) ) (?&spaces) )
)
\A (?&spaces) (?: (?&array) | (?&object) ) (?&spaces) \z
/sx;
'123' =~ $json_regex and die;
qq'["\003"]' =~ $json_regex and die;
qq'[\xA0]' =~ $json_regex and die;
qq'[TRUE]' =~ $json_regex and die;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment