1

Here is my data :

'%%case.r_object_id%%' and  application_phase = '%%case.status%%'  and rp.quality =  '%%case.<reno_application_person>.<child>.quality%%

I want to get all the objects enclosed in double percent %%, we have 3.

Based on my implementation, matcher.find() finds the first %% and the last %% in the string. So its just one loop. How can i adjust my regex or code to ensure i get 3 matches ?

Matcher matcher = Pattern.compile("(%%[^\"\n]+%%)").matcher(results);

    while (matcher.find()) {
                try {
                    matcher.appendReplacement(stringbuffer, getReplacementStringValue(matcher.group().replaceAll("%", "")));
                } catch (DocumentGeneratorException e1) {
                    e1.printStackTrace();
                }
            }
Undisputed007
  • 639
  • 1
  • 10
  • 31

2 Answers2

1

If you use a reluctant quantifier after your custom class, the parser should match at the next occurrence of the double %% rather than go through the entire string: "(%%[^\"\n]+?%%)".

Note the question mark after the +.

Also remember to:

matcher.appendTail(stringbuffer)

... once you're done!

Docs

See the "quantifiers" sections of the documentation.

Mena
  • 47,782
  • 11
  • 87
  • 106
1

Did you mean this regex %%(.*?)%%:

String regex = "%%(.*?)%%";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {                                                
    System.out.println(matcher.group(1));
    //                               ^------note to get the group one
}

Outputs

case.r_object_id
case.status
case.<reno_application_person>.<child>.quality
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140