2014-07-01 50 views
0
public class StringExample 
{ 
    public static void main(String[] args) 
    { 
     String x = "^^^"; 
     String y = "~"; 
     String s = "abc^^^xyz"; 
     if (s != null && s.indexOf(x) > -1) 
      s = s.replaceAll(x,y); 
     System.out.println("s :" + s); 
    } 
} 

它沒有給出正確的結果。想要用「〜」替換「^^^」說abc ^^^ xyz應該被替換爲abc〜xyz

  • 輸入

    ABC ^^^ XYZ

  • 實際輸出

    〜A〜B〜C〜^〜^〜^〜X〜ÿ 〜z

  • 期望輸出

    ABC〜XYZ

+3

的replaceAll()接受一個正則表達式作爲參數..你需要躲避'^單曲 – TheLostMind

+1

什麼,我不明白的是,爲什麼你做了''aaa ^^^ bbb「.replaceAll(」^^^「,」〜「)''你有''a〜b〜c〜^〜^〜^〜x〜y〜z',而不是'〜aaa ^^^ bbb'? – Kent

回答

4

使用replace代替replaceAll。後者採用正則表達式,其中^是保留字符。

+0

我責備Sun誤導方法命名。 –

+0

@KarolS'replace'在Java的更高版本中添加。屆時,重命名'replaceAll'已經太遲了。 – shmosel

0

試試這個:

String str = "abc^^^xyz"; 
String replaceAll = str.replaceAll("\\^+", "~"); 

注:所有你需要的是逃避CHAR(^

0

逃離^字符。

public class StringExample { 
    public static void main(String[] args) { 
     String x = "\\^\\^\\^"; 
     String y = "~"; 
     String s = "abc^^^xyz"; 
     if (s != null && s.indexOf(x) > -1) 
      s = s.replaceAll(x,y); 
     System.out.println("s :" + s); 
    } 
} 
0

s= s.replaceAll("\\^{3}","~"); 

s=s.replace("^^^","~"); 
實際上

,所述replace()方法調用replaceAll()內部。

並且您可以保存s.indexOf(x) > -1支票。在地方

1

使用replace()replaceAll()

s = s.replace(x,y); 
0

儘管你應該在這種情況下使用replace(x,y)而不是replaceAll(x,y),你仍然可以使用replaceAll(),只是引用了第一個參數。

這會將正則表達式轉換爲文字字符串。

Pattern.quote(x) 

quote() will escape reserved;正則表達式字符,像這樣:

\Q^^^\E 

實例的完整性:

import java.util.regex.Pattern; 

public class StringExample { 
    public static void main(String[] args) { 
     String x = "^^^"; 
     String y = "~"; 
     String s = "abc^^^xyz"; 

     if (s != null && s.indexOf(x) > -1) { 
      s = s.replaceAll(Pattern.quote(x), y); 
     } 
     System.out.println("s :" + s); 
    } 
} 
相關問題