[英]Right using of String lastIndexOf
I have string String str ="12,123 123!abc123.abc"
with ,.!
我的字符串
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. 定界符,我想删除最后一个123。如果我使用
StringBuffer str1c = new StringBuffer(str)
并使用int last = str1c.lastIndexOf("123")
我将得到last =14。但这是错误的,因为要获取索引清除为“ 123”,附近没有任何字母。 I want to make str1c ="12,123 !abc123.abc"
我想使
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: 您将需要使用正则表达式,并且仅需替换最后一个匹配项,因此您将需要使用
StringBuilder#reverse()
反转所有内容并使用反向的正则表达式,因此无需使用\\b321\\b
\\b123\\b
而是使用\\b321\\b
,因此您的最终代码将是:
String result = new StringBuilder(
new StringBuilder(str).reverse().toString().replaceFirst("\\b321\\b", "")
).reverse().toString();
System.out.println(result);
Output: 输出:
12,123 !abc123.abc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.