2
{{"name":"alpha",
 "age":"23",
 "sex":male",
 "location":"U.S"
 }
 {"name":"beta",
 "age":"23",
 "sex":male",
 "location":"Cambodia"
}}

If I give a name, my regex should return the location for that name. Suppose the name is given as a variable, then I try,

"name":"alpha"[\d\D]*"location":"(.+?)"

I always get the last location with this expression. How can I get the location based on the name? Any help?

user2626431
  • 447
  • 1
  • 10
  • 20
  • 2
    Don't use regex to extract data from JSON. – trincot Sep 29 '16 at 22:06
  • 2
    Possible duplicate of [What do lazy and greedy mean in the context of regular expressions?](http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions) – revo Sep 29 '16 at 22:06
  • @trincot What if you only have regexes available? Okay, you can write a full JSON parser but that's a bit overkill for extracting a string from some JSON data. – Mecki Sep 29 '16 at 22:10
  • @user2626431, can you please specify the programming environment you are using? – trincot Sep 30 '16 at 15:09

1 Answers1

2

You always get the last one because [\d\D]* is matching everything in between and Regexes try to always match as much as possible. If your Regex engine knows about non-greedy matches (and it looks like it does because you use a non-greedy match at the location yourself: +?), you should be able to use this:

"name":"alpha"[\d\D]*?"location":"(.+?)"
Mecki
  • 125,244
  • 33
  • 244
  • 253