programing

String replace()와 replaceAll()의 차이점

javaba 2022. 7. 17. 12:12
반응형

String replace()와 replaceAll()의 차이점

javajava.lang의 의 " " " "replace() ★★★★★★★★★★★★★★★★★」replaceAll()regex" "regex" "" "regex" "" "regex" "regex" 와 간단한 치환의 경우 "regex" 를 바꿉니다../

그럼,replace는 한 한 쌍의 합니다.CharSequence(String) (String) (String) (String) (String) (String) (String (String)replace 또는 method char 의 char 、 char 、 char 、 char 、 char 의의의의의의의의의의 method method method method method all all all all all all all all all CharSequence반면 첫 번째는StringreplaceFirst ★★★★★★★★★★★★★★★★★」replaceAll정규 표현(regex)입니다.잘못된 기능을 사용하면 미묘한 버그가 발생할 수 있습니다.

Q: q q의 차이점은 무엇입니까?java.lang.String '''」replace() ★★★★★★★★★★★★★★★★★」replaceAll()를 사용하는 것 에는 regex.를 사용합니다

A: 그냥 정규식이야. 다 모두 교체됩니다. : )

http://docs.oracle.com/javase/8/docs/api/java/lang/String.html

PS:

'아주머니'라는 것도 있어요.replaceFirst()가 필요하다

다.replace() ★★★★★★★★★★★★★★★★★」replaceAll()스트링 string string string string string string string string string 。

나는 항상 차이점을 이해하는 데 도움이 되는 사례를 발견한다.

replace()

replace() 의 교환을 char 한 번char 몇 가지 (일부)String 한 번String는)CharSequence를 참조해 주세요.

예 1

문자의 모든 항목을 바꿉니다.xo

String myString = "__x___x___x_x____xx_";

char oldChar = 'x';
char newChar = 'o';

String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_

예 2

.fishsheep

String myString = "one fish, two fish, three fish";

String target = "fish";
String replacement = "sheep";

String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep

replaceAll()

replaceAll()정규 표현 패턴을 사용하는 경우.

예 3

를 R&D로 .x.

String myString = "__1_6____3__6_345____0";

String regex = "\\d";
String replacement = "x";

String newString = myString.replaceAll(regex, replacement); 
// __x_x____x__x_xxx____x

예 4

모든 공백을 제거합니다.

String myString = "   Horse         Cow\n\n   \r Camel \t\t Sheep \n Goat        ";

String regex = "\\s";
String replacement = "";

String newString = myString.replaceAll(regex, replacement); 
// HorseCowCamelSheepGoat

「 」를 참조해 주세요.

문서

정규 표현

replace()둘다인 것을 수 .char a. a. a.CharSequence인수로써.

한, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」replace()replaceAll()후자는 regex 패턴을 컴파일한 후 최종적으로 치환하기 전에 일치하기 때문에 전자는 단순히 지정된 인수와 일치하여 치환하기 때문입니다.

더 에 regex의 매칭이 은 regex 패턴의 매칭입니다.replace()에 걸쳐서replaceAll()가능한 한 제안합니다.

예를 들어, 말씀하신 것처럼 간단한 치환의 경우 다음을 사용하는 것이 좋습니다.

replace('.', '\\');

다음 대신:

replaceAll("\\.", "\\\\");

주의: 위의 변환 방식 인수는 시스템에 따라 다릅니다.

  1. replace()와 replaceAll() 모두 2개의 인수를 받아들여 문자열 내의 첫 번째 서브스트링(첫 번째 인수)을 두 번째 서브스트링(두 번째 인수)으로 바꿉니다.
  2. replace()는 char 또는 charsequence 쌍을 받아들이고 replaceAll()은 regex 쌍을 받아들입니다.
  3. replace()가 replaceAll()보다 더 빠르게 동작하는 것은 아닙니다.이는 둘 다 구현에서 동일한 코드를 사용하기 때문입니다.

    pattern.compile(regex).matcher(이것). replaceAll(대체);

여기서 문제는 replace를 사용할 때와 replace All()을 사용할 때입니다.문자열 내의 발생 위치에 관계없이 서브스트링을 다른 서브스트링으로 대체할 경우 replace()를 사용합니다.단, 문자열의 선두 또는 끝에 있는 서브스트링만 replaceAll()을 사용하여 교환하는 등의 특별한 프리퍼런스나 조건이 있는 경우에는 replaceAll()을 사용합니다.다음은 제 요점을 증명하는 몇 가지 예입니다.

String str = new String("==qwerty==").replaceAll("^==", "?"); \\str: "?qwerty=="
String str = new String("==qwerty==").replaceAll("==$", "?"); \\str: "==qwerty?"
String str = new String("===qwerty==").replaceAll("(=)+", "?"); \\str: "?qwerty?"
String replace(char oldChar, char newChar)

이 문자열에 포함된 모든 oldChar를 newChar로 대체한 새 문자열을 반환합니다.

String replaceAll(String regex, String replacement

지정된 정규 표현과 일치하는 이 문자열의 각 하위 문자열을 지정된 대체 문자열로 바꿉니다.

아래 코드에 대해 두 가지 모두 어떻게 기능하는지 예를 들어 설명하려면:

public static void main(String[] args)
{
    String s = "My\\s aaab\\s is\\s aaab\\s name";
    String s1 = s.replace("\\s", "c");
    System.out.println(s1);
    String s2 = s.replaceAll("\\s", "c");
    System.out.println(s2);
}

출력:

Myc aaabc isc aaabc name
My\scaaab\scis\scaaab\scname

설명.

s.replace는 "\\s" 문자 시퀀스를 c로 바꿉니다.따라서 첫 번째 줄 s.replaceAll의 출력은 \s를 (공간에 상당하는) regex로 간주하고 string s의 \s로 공간을 바꿉니다.\s는 첫 번째 \s와 함께 이스케이프되어 \s가 됩니다.

Intelij Idea는 스마트하게 사용법을 알려줍니다.아래 이미지를 자세히 보면 replace All과 replace All 사용 방법에 대한 Intelliz 아이디어의 해석 차이를 알 수 있습니다.

여기에 이미지 설명 입력

wickeD의 답변에서 알 수 있듯이 replaceAll을 사용하면 replaceAll과 replaceAll 사이에서 모든 치환 문자열이 다르게 처리됩니다.a[3]와 a[4]의 값이 같을 줄 알았는데 다릅니다.

public static void main(String[] args) {
    String[] a = new String[5];
    a[0] = "\\";
    a[1] = "X";
    a[2] = a[0] + a[1];
    a[3] = a[1].replaceAll("X", a[0] + "X");
    a[4] = a[1].replace("X", a[0] + "X");

    for (String s : a) {
        System.out.println(s + "\t" + s.length());
    }
}

이 출력은 다음과 같습니다.

\   1
X   1
\X  2
X   1
\X  2

이는 교환 시 추가 수준의 이스케이프가 필요하지 않은 perl과는 다릅니다.

#!/bin/perl
$esc = "\\";
$s = "X";

$s =~ s/X/${esc}X/;
print "$s " . length($s) . "\n";

인쇄 \x 2

이는 java.sql에서 반환된 값을 사용하려고 할 때처럼 매우 번거로울 수 있습니다.DatabaseMetaData.getSearchStringEscape()를 replaceAll()로 지정합니다.

Java 9 에서는, 치환 방식의 최적화가 몇개인가 행해지고 있습니다.

Java 8에서는 정규식을 사용합니다.

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

Java 9 이후.

여기에 이미지 설명 입력

Stringlatin 구현도 가능합니다.

여기에 이미지 설명 입력

어느 쪽이 훨씬 더 나은지.

https://medium.com/madhash/composite-pattern-in-a-nutshell-ad1bf78479cc?source=post_internal_links---------2------------------

오래된 스레드는 알지만 자바에 익숙하지 않아서 이상한 것 중 하나를 발견합니다.사용한 적이 있다String.replaceAll()예측할 수 없는 결과를 얻을 수 있습니다.

이런 게 끈을 뒤죽박죽으로 만들죠

sUrl = sUrl.replaceAll( "./", "//").replaceAll( "//", "/");

그래서 이상한 문제를 피하기 위해 이 기능을 설계했습니다.

//String.replaceAll does not work OK, that's why this function is here
public String strReplace( String s1, String s2, String s ) 
{
    if((( s == null ) || (s.length() == 0 )) || (( s1 == null ) || (s1.length() == 0 )))
     { return s; }

   while( (s != null) && (s.indexOf( s1 ) >= 0) )
    { s = s.replace( s1, s2 ); }
  return s;
}

이를 통해 다음 작업을 수행할 수 있습니다.

sUrl=this.strReplace("./", "//", sUrl );
sUrl=this.strReplace( "//", "/", sUrl );

replace()method는 regex 패턴을 사용하지 않습니다.replaceAll()method는 regex 패턴을 사용합니다.그렇게replace()보다 고속으로 동작합니다.replaceAll().

이미 선택된 "Best Answer"(및 Suragch와 같은 우수한 답변)에 추가하려면String.replace()연속적인 문자를 치환함으로써 제약된다(순차적 취득).CharSequence단,String.replaceAll()는 시퀀셜 문자만 치환해도 제약되지 않습니다.정규식이 이러한 방식으로 구성되어 있으면 순차적이지 않은 문자를 대체할 수 있습니다.

또한 (가장 중요하고 고통스러울 정도로 명백한)replace()할 수 있습니다.단, 리터럴 값은 치환할 수 없습니다.replaceAll는, 「like」시퀀스를 치환할 수 있습니다(꼭 동일할 필요는 없습니다).

replace는 char 데이터 유형에서 작동하지만 replaceAll은 String 데이터 유형에서 작동하며 둘 다 첫 번째 인수의 모든 항목을 두 번째 인수로 바꿉니다.

언급URL : https://stackoverflow.com/questions/10827872/difference-between-string-replace-and-replaceall

반응형