This question is a derivation from another question in this forum which I thought was quite simple, but in the end found out a difficult one.
OP asked to replace any text xyz from the all substrings <tagname>xyz</tagname> with some NEW TEXT. I did the following:
String str="<tagname>bgerh</tagname>sdfghuhjg<tagname>bgew</tagname>rwesdgrhtf<tagname>bfgh</tagname>";
System.out.println(str.replaceAll("(?<=(<tagname>)).*(?=(</tagname>))","NEW TEXT"));
The output I got:
<tagname>NEW TEXT</tagname>
which is obviously not the desired one.
So, I would like to know if the regex checking happen from both the ends of a string, and I will bbe delighted with a solution to the example.
Thanks in advance.
.*is a greedy quantifier, meaning it will match everything it can. Because your sample string begins with<tagname>and ends with</tagname>, everything in between will be matched by.*.To fix this, you can instead use a reluctant quantifier, and it will only grab as little as it can. The reluctant qualifier looks like this:
.*?, and thus the entire expression would look like this: