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'}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
EdgarDrake
  • 89
  • 1
  • 6

1 Answers1

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

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188