programing

java replaceLast ()

projobs 2021. 1. 18. 07:31
반응형

java replaceLast ()


이 질문에 이미 답변이 있습니다.

거기에 replaceLast()자바로? 나는 거기 봤다 replaceFirst().

편집 : SDK에없는 경우 좋은 구현은 무엇입니까?


(물론) 정규식으로 수행 할 수 있습니다.

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", "--"));
    }
}

미리보기에 약간의 CPU주기가 필요 하지만 매우 큰 문자열로 작업 할 때만 문제가 될 것입니다 (그리고 검색되는 정규식의 많은 발생).

간단한 설명 (정규식의 경우 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

편집하다

오래된 게시물을 깨워서 죄송합니다. 그러나 이것은 겹치지 않는 인스턴스에만 해당됩니다. 예를 들어 .replaceLast("aaabbb", "bb", "xx");반환 "aaaxxb"하지"aaabxx"

사실, 다음과 같이 수정할 수 있습니다.

public class Test {

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

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

정규식이 필요하지 않은 경우 여기에 하위 문자열 대안이 있습니다.

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(), string.length());
    } else {
        return string;
    }
}

테스트 케이스 :

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
}

replaceAll을 사용하고 패턴 바로 뒤에 달러 기호를 추가하십시오.

replaceAll("pattern$", replacement);

다음 StringUtils.reverse()결합 할 수 있습니다.String.replaceFirst()


직접 확인 : String

아니면 실제로 "어떻게 구현 replaceLast()합니까?"

구현을 시도해 보겠습니다 ( 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();
}

아파치에서 StringUtils 사용 :

org.apache.commons.lang.StringUtils.chomp(value, ignoreChar);

아니.

reverse/ replaceFirst/ 할 수 reverse있지만 약간 비쌉니다.


검사 된 문자열이

myString.endsWith(substringToReplace) == true

당신은 또한 할 수 있습니다

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

느리지 만 작동합니다 .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;
}

미리보기 정규식을 사용하여 바늘로 건초 더미를 분할하고 배열의 마지막 요소를 바꾼 다음 다시 결합하십시오.

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);

나는 또한 그러한 문제가 발생했지만 다음 방법을 사용합니다.

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();
}

It really works good. Just add your string where u want to replace string in s and in place of "he" place the sub string u want to replace and in place of "mt" place the sub string you want in your new string.

import java.util.Scanner;

public class FindSubStr 
{
 public static void main(String str[])
 {
    Scanner on=new Scanner(System.in);
    String s=on.nextLine().toLowerCase();
    String st1=s.substring(0, s.lastIndexOf("he"));
    String st2=s.substring(s.lastIndexOf("he"));
    String n=st2.replace("he","mt");

    System.out.println(st1+n);
 }

}

ReferenceURL : https://stackoverflow.com/questions/2282728/java-replacelast

반응형