Regex for either the word null, or a string in double quotes

Viewed 54

I'm searching a block of text in JSON format. It may be easier to do this another way, but I'm looking to see if this is possible. I'm using preg_match_all() in PHP 7.x, but this is more of a regex problem.

Sometimes the string in the text is like this "something":"a string, here!", and other times it is like this "something":null, .

For the first case, this will work...

/"something":"([^"]*)",/

For the second case, this will work...

/"something":null,/

or

/"something":([^,]*),/

Is there a way to match either cases in the same regex?

Something like this doesn't work...

/"something":"?(null|[^"]*)?"?,/

And the string can have commas in it, and this doesn't work...

/"something":(null|[^,]*),/

Anyone know if this is possible? Thanks.

1 Answers

The fact you are using PHP is crucial as you can use

"something":(?|"([^"]*)"|(null)),

See the regex demo.

Details:

  • "something": - a literal string
  • (?|"([^"]*)"|(null)) - a branch reset group: ", Group 1: any zero or more chars other than a ", then a " or null string also captured into Group 1
  • , - a comma.
Related