简体   繁体   中英

Right using of String lastIndexOf

I have string String str ="12,123 123!abc123.abc" with ,.! 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", "")
).reverse().toString();
System.out.println(result);

Output:

12,123 !abc123.abc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM