0

I'm trying to match a pattern in a Java string (a json one). This pattern matches in the string several times, but it also matches with a string that contains the others. Let me explain myself with an example.

    String json = "IRRELEVANT_TEXT{'/element|1717_todossavoy/480/': {item_url:'/element|1717_Lorem/64/', item_description: 'Lorem ipsum dolor sit amet'},'/element|1717_Marcrie/480/': {item_url:'/element|1717_Vestibulum/64/', item_description: ' Vestibulum enim tellus, sodales sit amet consequat ut'},'/element|1717_Cannes05/434/': {item_url:'/element|1717_Nullam/64/', item_description: 'Nullam gravida risus vehicula nisi egestas'},'/element|1717_babelsavoy/266/': {item_url:'/element|1717_Pellentesque/64/', item_description: 'Pellentesque habitant morbi tristique senectus'}};IRRELEVANT";
    Matcher matcher = Pattern.compile("/element.*480/").matcher(json);
    while(matcher.find()) {
        System.out.println(matcher.group());
    }

I am getting the following:

/element|1717_todossavoy/480/': {item_url:'/element|1717_Lorem/64/', item_description: 'Lorem ipsum dolor sit amet'},'/element|1717_Marcrie/480/

But I'd like to get the 2 following keys:

/element|1717_todossavoy/480/
/element|1717_Marcrie/480/

What am I doing wrong?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
hosseio
  • 1,142
  • 2
  • 12
  • 25

1 Answers1

4

.* is greedy and will try to match as much as possible. You can make it reluctant/ungreedy by appending a question mark. .*?.

However, this still won't give you what you want because /element|1717_Lorem/64/ will match up to 480. A better regex would probably be

/element[^/]+/480/
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405