Java 替换另一个字符串中最后一次出现的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23325800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:57:04  来源:igfitidea点击:

Replace the last occurrence of a string in another string

javaregexstring

提问by Magnus

Let's say I have a string

假设我有一个字符串

string myWord="AAAAA";

I want to replace "AA" with "BB", but only the last occurrence, like so:

我想用“BB”替换“AA”,但只有最后一次出现,如下所示:

"AAABB"

Neither string.replace()nor string.replaceFirst()would do the job. Is there a string.replaceLast()? And, If not, will there ever be one or is there an alternative also working with regexes?

无论是与string.replace()也不string.replaceFirst()会做这项工作。有string.replaceLast()吗?而且,如果没有,是否会有一个或者是否有另一种也可以使用正则表达式?

采纳答案by Sotirios Delimanolis

Find the index of the last occurrence of the substring.

查找子字符串最后一次出现的索引。

String myWord = "AAAAAasdas";
String toReplace = "AA";
String replacement = "BBB";

int start = myWord.lastIndexOf(toReplace);

Create a StringBuilder(you can just concatenate Strings if you wanted to).

创建一个StringBuilder(如果需要,您可以连接字符串)。

StringBuilder builder = new StringBuilder();

Append the part before the last occurrence.

在最后一次出现之前追加该部分。

builder.append(myWord.substring(0, start));

Append the Stringyou want to use as a replacement.

附加String您要用作替换的。

builder.append(replacement);

Append the part after the last occurrence from the original `String.

在原始字符串中最后一次出现之后追加该部分。

builder.append(myWord.substring(start + toReplace.length()));

And you're done.

你已经完成了。

System.out.println(builder);

回答by Amit Joki

You can do this:

你可以这样做:

myWord = myWord.replaceAll("AA$","BB");

$means at the last.

$最后的意思。

回答by Flash Thunder

String string = "AAAAA";
String reverse = new StringBuffer(string).reverse().toString();
reverse = reverse.replaceFirst(...) // you need to reverse needle and replacement string aswell!
string = new StringBuffer(reverse).reverse().toString();

回答by Asif Bhutto

You can do this with String#subtring

你可以这样做 String#subtring

myWord= myWord.substring(0, myWord.length() - 2) + "BB";

回答by Anirudha

myWord=myWord.replaceAll("AA(?!A)","BB");

回答by Biswajit_86

Just get the last index and do an in place replacement of the expression with what you want to replace.

只需获取最后一个索引并用您要替换的内容就地替换表达式。

myWordis the original word sayAABDCAADEF. sourceWordis what you want to replace, say AAtargetWordis what you want to replace it with say BB.

myWord是原词say AABDCAADEFsourceWord是您要替换的内容, sayAAtargetWord是您要替换的内容 say BB

StringBuilder strb=new StringBuilder(myWord);    
int index=strb.lastIndexOf(sourceWord);    
strb.replace(index,sourceWord.length()+index,targetWord);    
return strb.toString();

This is useful when you want to just replace strings with Strings.A better way to do it is to use Pattern matcher and find the last matching index. Take as substring from that index, use the replace function there and then add it back to the original String. This will help you to replace regular expressions as well

当您只想用字符串替换字符串时,这很有用。更好的方法是使用模式匹配器并找到最后一个匹配的索引。从该索引中获取子字符串,在那里使用替换函数,然后将其添加回原始字符串。这也将帮助您替换正则表达式

回答by wns349

It seems like there could be a regex answer to this.

似乎有一个正则表达式可以解决这个问题。

I initially was trying to solve this through regex, but could not solve for situations like 'AAAzzA'.

我最初试图通过正则表达式解决这个问题,但无法解决像“AAAzzA”这样的情况。

So I came up with this answer below, which can handle both 'AAAAA' and 'AAAzzA'. This may not be the best answer, but I guess it works.

所以我在下面想出了这个答案,它可以处理“AAAAA”和“AAAzzA”。这可能不是最好的答案,但我想它有效。

The basic idea is to find the last index of 'AA' occurrence and split string by that index:

基本思想是找到 'AA' 出现的最后一个索引并通过该索引拆分字符串:

String myWord = "AAAAAzzA";
String source = "AA";
String target = "BB";
int lastIndex = -1;
if ((lastIndex = myWord.lastIndexOf(source)) >= 0) {
    String f = myWord.substring(0, lastIndex);
    String b = myWord.substring(lastIndex + target.length() >= myWord
            .length() ? myWord.length() : lastIndex + target.length(),
            myWord.length());
    myWord = f + target + b;
}
System.out.println(myWord);