0

I have the following json,

{"master": "abc", "current": "abc", "total":[{"name":"abc"},{"name":"xyz"}]}

Now I need to validate the above json using a regular expression, that is, I need to confirm that the master value and current value are the same (in the above json both master and current has "abc" as value) and I don't care about the rest of the json

can anyone help me out with such a regex

user1810502
  • 531
  • 2
  • 7
  • 19
  • 4
    that is the job for json parser/validator, not for regex – mvp Dec 25 '13 at 01:12
  • 1
    plain regex is not capable of doing that. Json cannot be descriped as a regular language, since regex is not context-sensitive – pogopaule Dec 25 '13 at 01:15
  • I am in a situation where I only need a regex, but from above comments it looks like this is not possible with regex. Thanks. – user1810502 Dec 25 '13 at 01:17
  • @user1810502 You can use regex to get the values of `master` and `current` then use another tool to check if they are the same – rullof Dec 25 '13 at 01:22
  • @pogopaule: regexes haven't been regular for a long time. I'm not saying that regexes are a good tool for this task, just that regularity and "parseable with a regex" aren't that closely related anymore. – mu is too short Dec 25 '13 at 01:31
  • 1
    @pogopaule Check this [**answer**](http://stackoverflow.com/a/3845829). I can provide you with more if you want to. Make sure to check [the true **power** of regex](http://nikic.github.io/2012/06/15/The-true-power-of-regular-expressions.html) :) – HamZa Dec 25 '13 at 01:50

1 Answers1

0

You could use something like this:

("master": "([^"]*)")+.*"current": "([^"]*)"

Try it here: http://regexr.com?37pbn

Then you can pull out the values into variables and compare them. However, if "master" might come after "current", you might want to pull the values out separately. Still, I would suggest that you use a parser.

If you do use RegEx, you might want to turn on case insensitivity and such.

HamZa
  • 14,671
  • 11
  • 54
  • 75
nikitab
  • 21
  • 1
  • according to www.json.org, `{` `}`-enclosed "objects" are unordered, so I'd hazard that your advice about "pull[ing] the values out separately" need be followed - a parser shouldn't depend on "master" being before "current", nor any particular ordering relative to "total", "name" or other tags that might be introduced later. Other edge cases relate to quoting... e.g. differentiating "old\"master" from "master", and skipping over objects and/or arrays when string values may contain '[' ']' '{' and/or '}' characters. That's why a json parser is preferable for robust behaviour. – Tony Delroy Dec 25 '13 at 01:45