0

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?

3
  • 2
    What if you remove i++ and use group(0)? Commented Apr 26, 2016 at 6:44
  • @npinti : It worked. Thanks. :) Commented Apr 26, 2016 at 7:03
  • Had there been one more variable, there would have been error.. Commented Apr 26, 2016 at 7:05

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.