I am not good in regular expressions and I need help in replacing the string.
String str = "Name_XYZ_";
str = "XYZ_NAME_";
So how can I replace "Name_" or "_NAME_" from above two strings with empty string?
The conditions are "Name" can be in any case and it can be at index 0 or at any index but preceded by "_".
So far I tried,
String replacedString = str.replaceAll("(?i)Name_", ""); // This is not correct.
This is not the homework. I am working on XML file that needs such kind of processing.
You were close. What you have to do is either anchor
nameto the beginning of the string (with^) or require an underscore there. I also changedNametoname, because why mix lower and upper case, if you are treating the pattern case-insenstively anyway. Note that?:is just an optimization (and a good practice). It suppresses capturing which you don’t need in this case.If you want to improve your regex skills, I can highly recommend this tutorial.