0

I create a regex to match a string, now I need to extract n times a group of characters from the string.

Something like this:

{"Group 1":{"Name":"A","Name":"B",....,"Name":"Z"},{"Group 2":{"Name":"AA","Name":"BB",....,"Name":"ZZ"}}

I create the regex \\"Group 1.\*?\\} now I want to extract all the names from group 1 only with this rule Name\\":\\"(.\*?)\\".

If I use \\"Group 1.\*?Name\\":\\"(.\*?)\\".\*?\\} it only extracts the first result, but I need all of them.

Any idea? Thanks

aalbagarcia
  • 975
  • 6
  • 17
  • 1
    Use a JSON parser for this, not regex. – Tim Biegeleisen Dec 12 '20 at 06:03
  • 1
    This is a classic case for a JSON parser. What language do you use? – Peter Thoeny Dec 12 '20 at 06:55
  • It isn't JSON, it's JS, I'm using Python and I need only one regex expresion, the case it's only an example not real case, the real string is a JS of one HTML, too large for put here – Adolfo Bellani Dec 12 '20 at 13:33
  • This is actually an interesting question. `preg_match_all('#\{"Group.*?\:\{("Name"\:"([a-z]*)").*?\}#i', $str, $matches);` returns only A and AA. There is a way to get what you want by inserting ?R properly which I am not able to figure out. https://stackoverflow.com/questions/8440911/recursive-php-regex – anjanesh Dec 13 '20 at 06:21
  • Thanks @anjanesh, it's look fine – Adolfo Bellani Dec 13 '20 at 16:03

1 Answers1

0

Depth 1 only. Not the right solution for n-depth.

<?php
$str = '{"Group 1":{"Name":"A","Name":"B",....,"Name":"Z"}},{"Group 2":{"Name":"AA","Name":"BB",....,"Name":"ZZ"}}';

# preg_match_all('#\{"Group.*?\:\{("Name"\:"([a-z]*)").*?\}\}#i', $str, $matches);
# print_r($matches);

preg_match_all('#\{"Group.*?\:\{(.*?)\}\}#i', $str, $matches_outer);
print_r($matches_outer);
foreach ($matches_outer[1] as $m)
{
    preg_match_all('#"Name"\:"([a-z]*)".*?#i', $m, $matches);
    print_r($matches);
}
?>

Also, you have missed a } in your original string. There should be a } after ,"Name":"Z"}

{"Group 1":{"Name":"A","Name":"B",....,"Name":"Z"}},{"Group 2":{"Name":"AA","Name":"BB",....,"Name":"ZZ"}}
anjanesh
  • 2,293
  • 5
  • 34
  • 42