manutd
manutd

Reputation: 291

Pattern matcher is not giving expected output

I have the below code.

String testdata = "%%%variable1%%% is not equal to %%%variable2%%%";
Pattern p = Pattern.compile("\\%%%(.*?)\\%%%");
Matcher m = p.matcher(testdata);
String variables = "";
int i = 0;
while (m.find()) {
    System.out.println(m.group());
    variables=m.group().replaceAll("%%%", "");
    System.out.println(variables);
    i++;
}

I am trying to print the string inside two %%%. So I am expecting below output:

%%%variable1%%% 
variable1 
%%%variable2%%% 
variable2

But the actual output is:

%%%variable1%%%
variable1
variable2
variable2

Why is it so? What is the problem with this?

Upvotes: 0

Views: 57

Answers (1)

rock321987
rock321987

Reputation: 11032

You need to remove i. There is no need of it

while (m.find()) {
      System.out.println(m.group());
      String variables=m.group().replaceAll("%%%", "");
      System.out.println(variables);
}

Ideone Demo

You don't also need replaceAll because what you require is already in first capturing group

while (m.find()) {
     System.out.println(m.group());
     System.out.println(m.group(1));
}

Ideone Demo

Upvotes: 4

Related Questions