0

Regex to validate JSON I am trying to write a regular expression to valide a json file. By searching in the internet , i got the above question.I am new to php and regex.

$pcre_regex = '
 /
 (?(DEFINE)
 (?<number>   -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )    
 (?<boolean>   true | false | null )
 (?<string>    " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
 (?<array>     \[  (?:  (?&json)  (?: , (?&json)  )*  )?  \s* \] )
 (?<pair>      \s* (?&string) \s* : (?&json)  )
 (?<object>    \{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \s* \} )
 (?<json>   \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) )     \s* )
 )
 \A (?&json) \Z
 /six   
';

In the above code , i cant able to understand what is /six and \A (?&json) \Z .. Anyone please help me.

Community
  • 1
  • 1
Gibbs
  • 21,904
  • 13
  • 74
  • 138

1 Answers1

3

It is not six. It is s, i, and x. They're pattern modifiers.

From the PHP manual documentation on Pattern Modifiers:

s (PCRE_DOTALL) If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

i (PCRE_CASELESS) If this modifier is set, letters in the pattern match both upper and lower case letters.

x (PCRE_EXTENDED) If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored.

\A is similar to ^, but if you have a string that spans several lines, \A matches the beginning of the entire string, as opposed to just a line beginning.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • Thanks Amal. Now i learned abot modifiers by googling it .. Thank you. I just don't know that is modifier. – Gibbs Apr 17 '14 at 06:27
  • @user3168736: No problem. Why are you using a regex to validate JSON though? – Amal Murali Apr 17 '14 at 06:33
  • My mentor wants me to validate a json file .. i thought java is the best choice . when i start implementing , i learned that java doesn't support recursive regex. so i move onto php. I hope regex is the best way to validate syntax. isnt? – Gibbs Apr 17 '14 at 06:35
  • **No.** For PHP, use [this function](http://stackoverflow.com/a/6041773/1438393) instead. For Java, try [this one](http://stackoverflow.com/a/10174938/1438393). A regex is not the best way (although it can be faster if the JSON structure is *deeply* nested). – Amal Murali Apr 17 '14 at 06:38
  • 1
    Thanks Amal. Those two links helped me a lot. If i have any doubts that cannot be identified by googling , will ask in another question. :) :) – Gibbs Apr 17 '14 at 06:45