String replace ()와 replaceAll ()의 차이점
나중에 정규식을 사용하는 것 외에 java.lang.String replace()
과 replaceAll()
메소드 의 차이점은 무엇입니까 ? 교체 같은 간단한 대체의 경우 .
와 /
어떤 차이가?
에서 java.lang.String
의 replace
방법은 두 문자의 한 쌍 또는 한 쌍의 소요 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
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceAll(String regex, String replacement)
replaceFirst(String regex, String replacement)
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.
- 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).
- replace() accepts a pair of char or charsequence and replaceAll() accepts a pair of regex.
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
'Programing' 카테고리의 다른 글
SQL에서 count (column)과 count (*)의 차이점은 무엇입니까? (0) | 2020.05.09 |
---|---|
C ++에서 int를 열거 형으로 캐스팅하는 방법은 무엇입니까? (0) | 2020.05.09 |
좋은 Python ORM 솔루션은 무엇입니까? (0) | 2020.05.09 |
마크 다운 테이블의 줄 바꿈? (0) | 2020.05.09 |
힘내 : "당신이 누구인지 알려주세요"오류 (0) | 2020.05.09 |