1

I have this String (please note that I must use this as string, not converted to JSON).

String cats = "[{'_id':'abxyz','image':'http://127.0.0.1/abxyz.png','name':'Tabby Cat'},{'_id':'xyzr2','image':'http://127.0.0.1/abxr2.png','name':'Calico Cat'},{'_id':'ghjkl','image':'http://127.0.0.1/ghjkl.png','name':'Persian Cat'},{'_id':'ojr12','image':'http://127.0.0.1/ojr12.png','name':'Angora Cat'}]";

or for better readability: (there is no white space between object)

String cats =
"[{'_id':'abxyz','image':'http://127.0.0.1/abxyz.png','name':'Tabby Cat'},\
{'_id':'xyzr2','image':'http://127.0.0.1/abxr2.png','name':'Calico Cat'},\
{'_id':'ghjkl','image':'http://127.0.0.1/ghjkl.png','name':'Persian Cat'},\
{'_id':'ojr12','image':'http://127.0.0.1/ojr12.png','name':'Angora Cat'}]";

I want to extract the Calico Cat object using regex. I tried to use

String pattern = "{\'_id\':\'xyzr2\'.*}"

Unfortunately, the selection expands from Calico Cat to Angora Cat:

{'_id':'xyzr2','image':'http://127.0.0.1/abxr2.png','name':'Calico Cat'},\
{'_id':'ghjkl','image':'http://127.0.0.1/ghjkl.png','name':'Persian Cat'},\
{'_id':'ojr12','image':'http://127.0.0.1/ojr12.png','name':'Angora Cat'}

What kind of regex pattern I need to isolate only the Calico Cat? Expected result:

{'_id':'xyzr2','image':'http://127.0.0.1/abxr2.png','name':'Calico Cat'}
3
  • 3
    "I want to extract the Calico Cat object using regex." Why don't you want to use a JSON parser? That's the natural approach to, y'know, parsing JSON... Commented Jun 8, 2016 at 10:17
  • I'm curious, what's the reason that you don't want to parse this? Commented Jun 8, 2016 at 10:26
  • That's the limitation imposed by the challenge, that's why. Also to enhance my RegEx understanding. Commented Jun 9, 2016 at 3:24

1 Answer 1

1

You need to make it non-greedy to get smallest possible match

String pattern = "{\'_id\':\'xyzr2\'.*?}"

Regex explanation here.

Regular expression visualization


or use following regex

String pattern = "{\'_id\':\'xyzr2\'[^}]*}"

Regex explanation here.

Regular expression visualization


FYI : Always it's better to use json parser instead of hard coded regex, since the data is in valid json. Refer : How to parse JSON in Java

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.