java替换最后一个()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2282728/
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 05:39:12  来源:igfitidea点击:

java replaceLast()

javastring

提问by Carlos Blanco

Is there replaceLast()in Java? I saw there is replaceFirst().

有没有replaceLast()在Java中?我看到有replaceFirst()

EDIT: If there is not in the SDK, what would be a good implementation?

编辑:如果 SDK 中没有,什么是好的实现?

采纳答案by Bart Kiers

It could (of course) be done with regex:

它可以(当然)用正则表达式完成:

public class Test {

    public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement);
    }

    public static void main(String[] args) {
        System.out.println(replaceLast("foo AB bar AB done", "AB", "--"));
    }
}

although a bit cpu-cycle-hungrywith the look-aheads, but that will only be an issue when working with very large strings (and many occurrences of the regex being searched for).

虽然前瞻有点cpu-cycle-hungry,但这只会在处理非常大的字符串(以及正在搜索的许多正则表达式)时出现问题。

A short explanation (in case of the regex being AB):

简短说明(如果正则表达式为AB):

(?s)     # enable dot-all option
A        # match the character 'A'
B        # match the character 'B'
(?!      # start negative look ahead
  .*?    #   match any character and repeat it zero or more times, reluctantly
  A      #   match the character 'A'
  B      #   match the character 'B'
)        # end negative look ahead

EDIT

编辑

Sorry to wake up an old post. But this is only for non-overlapping instances. For example .replaceLast("aaabbb", "bb", "xx");returns "aaaxxb", not "aaabxx"

很抱歉唤醒旧帖子。但这仅适用于非重叠实例。例如.replaceLast("aaabbb", "bb", "xx");返回"aaaxxb",而不是"aaabxx"

True, that could be fixed as follows:

确实,可以按如下方式修复:

public class Test {

    public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)(.*)" + regex, "" + replacement);
    }

    public static void main(String[] args) {
        System.out.println(replaceLast("aaabbb", "bb", "xx"));
    }
}

回答by Joachim Sauer

See for yourself: String

你自己看: String

Or is your question actually "How do I implement a replaceLast()?"

或者你的问题实际上是“我如何实现一个replaceLast()?”

Let me attempt an implementation (this should behave pretty much like replaceFirst(), so it should support regexes and backreferences in the replacement String):

让我尝试一个实现(这应该表现得非常像replaceFirst(),所以它应该支持替换字符串中的正则表达式和反向引用):

public static String replaceLast(String input, String regex, String replacement) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    if (!matcher.find()) {
       return input;
    }
    int lastMatchStart=0;
    do {
      lastMatchStart=matcher.start();
    } while (matcher.find());
    matcher.find(lastMatchStart);
    StringBuffer sb = new StringBuffer(input.length());
    matcher.appendReplacement(sb, replacement);
    matcher.appendTail(sb);
    return sb.toString();
}

回答by Thomas

No.

不。

You could do reverse/ replaceFirst/ reverse, but it's a bit expensive.

你可以做reverse/ replaceFirst/ reverse,但它是一个有点贵。

回答by Mihir Mathuria

You can combine StringUtils.reverse()with String.replaceFirst()

您可以结合StringUtils.reverse()使用String.replaceFirst()

回答by BalusC

If you don't need regex, here's a substring alternative.

如果您不需要正则表达式,这里有一个子字符串替代方案。

public static String replaceLast(String string, String toReplace, String replacement) {
    int pos = string.lastIndexOf(toReplace);
    if (pos > -1) {
        return string.substring(0, pos)
             + replacement
             + string.substring(pos + toReplace.length());
    } else {
        return string;
    }
}

Testcase:

测试用例:

public static void main(String[] args) throws Exception {
    System.out.println(replaceLast("foobarfoobar", "foo", "bar")); // foobarbarbar
    System.out.println(replaceLast("foobarbarbar", "foo", "bar")); // barbarbarbar
    System.out.println(replaceLast("foobarfoobar", "faa", "bar")); // foobarfoobar
}

回答by Whimusical

If the inspected string is so that

如果检查的字符串是这样的

myString.endsWith(substringToReplace) == true

you also can do

你也可以

myString=myString.replaceFirst("(.*)"+myEnd+"$",""+replacement) 

回答by AvrDragon

it is slow, but works:3

它很慢,但有效:3

    import org.apache.commons.lang.StringUtils;

public static String replaceLast(String str, String oldValue, String newValue) {
    str = StringUtils.reverse(str);
    str = str.replaceFirst(StringUtils.reverse(oldValue), StringUtils.reverse(newValue));
    str = StringUtils.reverse(str);
    return str;
}

回答by MushyPeas

split the haystack by your needle using a lookahead regex and replace the last element of the array, then join them back together :D

使用前瞻正则表达式用针分割干草堆并替换数​​组的最后一个元素,然后将它们重新连接在一起:D

String haystack = "haystack haystack haystack";
String lookFor = "hay";
String replaceWith = "wood";

String[] matches = haystack.split("(?=" + lookFor + ")");
matches[matches.length - 1] = matches[matches.length - 1].replace(lookFor, replaceWith);
String brandNew = StringUtils.join(matches);

回答by PhantomKid

use replaceAll and add a dollar sign right after your pattern:

使用 replaceAll 并在您的模式后添加一个美元符号:

replaceAll("pattern$", replacement);

回答by xhay

I also have encountered such a problem, but I use this method:

我也遇到过这样的问题,不过我用的是这个方法:

public static String replaceLast2(String text,String regex,String replacement){
    int i = text.length();
    int j = regex.length();

    if(i<j){
        return text;
    }

    while (i>j&&!(text.substring(i-j, i).equals(regex))) {
        i--;
    }

    if(i<=j&&!(text.substring(i-j, i).equals(regex))){
        return text;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(text.substring(0, i-j));
    sb.append(replacement);
    sb.append(text.substring(i));

    return sb.toString();
}