Programing

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

lottogame 2020. 5. 9. 09:06
반응형

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


나중에 정규식을 사용하는 것 외에 java.lang.String replace()replaceAll()메소드 의 차이점은 무엇입니까 ? 교체 같은 간단한 대체의 경우 ./어떤 차이가?


에서 java.lang.Stringreplace방법은 두 문자의 한 쌍 또는 한 쌍의 소요 CharSequence(이 행복하게 문자열의 한 쌍을거야, 그래서 문자열 서브 클래스로되어있는) '들. replace메소드는 모든 문자 또는를 대체합니다 CharSequence. 반면에, 모두 String인수 replaceFirst하고 replaceAll정규 표현식 (정규식을)입니다. 잘못된 기능을 사용하면 미묘한 버그가 발생할 수 있습니다.


Q : 나중에 정규식을 사용하는 것 이외 java.lang.String방법 replace()의 차이점은 무엇입니까?replaceAll()

A : 정규식입니다. 그들은 모두 모두를 대체합니다 :)

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

추신:

또한 replaceFirst()(정규식이 필요합니다)


replace()메소드는 기본 요소 char와 a 를 모두 CharSequence인수 로 허용하도록 오버로드되었습니다 .

성능에 관한 한, 후자는 먼저 정규식 패턴을 컴파일 한 다음 최종적으로 교체하기 전에 일치하는 반면, 전자는 단순히 제공된 인수와 일치하고 대체하기 때문에 replace()방법이 약간 빠릅니다 replaceAll().

우리는 정규식 패턴 일치가 조금 더 복잡하고 결과적으로 느리다는 것을 알고 있으므로 가능할 때마다 선호 replace()하는 replaceAll()것이 좋습니다.

예를 들어, 당신이 언급 한 간단한 대체의 경우 다음을 사용하는 것이 좋습니다.

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

대신에:

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

참고 : 위의 변환 방법 인수는 시스템에 따라 다릅니다.


모두 replace()replaceAll()String의 모든 항목을 대체합니다.

차이점을 이해하는 데 도움이되는 예제가 항상 있습니다.

replace()

사용 replace()이 좀 바꾸려면 char서로 char또는 어떤 String다른과 String(사실을 CharSequence).

실시 예 1

모든 문자를 x바꿉니다 o.

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

모든 문자열을 fish바꿉니다 sheep.

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

Use replaceAll() if you want to use a regular expression pattern.

Example 3

Replace any number with an 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

Example 4

Remove all whitespace.

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

See also

Documentation

Regular Expressions


String replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String replaceAll(String regex, String replacement

Replaces each substring of this string that matches the given regular expression with the given replacement.


  1. Both replace() and replaceAll() accepts two arguments and replaces all occurrences of the first substring(first argument) in a string with the second substring (second argument).
  2. replace() accepts a pair of char or charsequence and replaceAll() accepts a pair of regex.
  3. It is not true that replace() works faster than replaceAll() since both uses the same code in its implementation

    Pattern.compile(regex).matcher(this).replaceAll(replacement);

Now the question is when to use replace and when to use replaceAll(). When you want to replace a substring with another substring regardless of its place of occurrence in the string use replace(). But if you have some particular preference or condition like replace only those substrings at the beginning or end of a string use replaceAll(). Here are some examples to prove my point:

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

As alluded to in wickeD's answer, with replaceAll the replacement string is handled differently between replace and replaceAll. I expected a[3] and a[4] to have the same value, but they are different.

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

The output of this is:

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

This is different from perl where the replacement does not require the extra level of escaping:

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

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

which prints \X 2

This can be quite a nuisance, as when trying to use the value returned by java.sql.DatabaseMetaData.getSearchStringEscape() with replaceAll().


Old thread I know but I am sort of new to Java and discover one of it's strange things. I have used String.replaceAll() but get unpredictable results.

Something like this mess up the string:

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

So I designed this function to get around the weird problem:

//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;
}

Which make you able to do:

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

replace() method doesn't uses regex pattern whereas replaceAll() method uses regex pattern. So replace() performs faster than replaceAll().


replace works on char data type but replaceAll works on String datatype and both replace the all occurrences of first argument with second argument.

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

반응형