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?

4
  • 2
    Don't use regex to extract data from JSON. Commented Sep 29, 2016 at 22:06
  • 2
    Possible duplicate of What do lazy and greedy mean in the context of regular expressions? Commented Sep 29, 2016 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. Commented Sep 29, 2016 at 22:10
  • @user2626431, can you please specify the programming environment you are using? Commented Sep 30, 2016 at 15:09

1 Answer 1

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":"(.+?)"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.