Vladislav Vladislav - 4 months ago 35
Java Question

Right using of String lastIndexOf

I have string

String str ="12,123 123!abc123.abc"
delimiters and I want to delete last 123. If I use
StringBuffer str1c = new StringBuffer(str)
and use
int last = str1c.lastIndexOf("123")
i'll get last = 14. But it is wrong, because want to get index of clear "123", without any letters near. I want to make
str1c ="12,123 !abc123.abc"


You will need to use a regular expression and as you need to only replace the last match, you will need to reverse everything using StringBuilder#reverse() and use a reversed regular expression so instead of using \b123\b we use \b321\b, so your final code will be:

String result = new StringBuilder(
    new StringBuilder(str).reverse().toString().replaceFirst("\\b321\\b", "")


12,123 !abc123.abc