2012-12-03 91 views
2

在我的java代碼中,我希望類似於如果字符串輸入有任何提及的特殊字符,應該在前面加上\

特殊字符集是{+, -, &&, ||, !, (,), {, },[, ], ^, "", ~, *, ?, :, \}。我嘗試使用inputString.replaceAll(old,new),但令我驚訝的是它不工作,即使我給予'舊'和'新'適當的值。

我把特殊字符放在一個字符串數組中,將它迭代到一個for循環中,檢查它是否存在於字符串中,如果是的話,input.replaceAll(":","\\:")。但它沒有給我預期的輸出。請幫忙。當String,replaceAll失敗時用特殊字符替換特殊字符

String[] arr = { "+", "-", "&&", "||", "!", "(", ")", "{", "}", 
        "[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" }; 

     for (int i = 0; i < arr.length; i++) { 
      System.out.println("arr[" + i + "]>>>>>>>>>>>>>>>" + arr[i]); 
      System.out.println(search.contains((String) arr[i]) 
        + "---------->" + arr[i]); 

      if (search.contains((String) arr[i])) { 
       System.out.println("..index..."+search.indexOf((String) arr[i])); 
       String oldString = (String) arr[i]; 
       System.out.println("check if it has old string" 
         + search.contains(oldString)); 
       String newString = new String("\\" + arr[i]); 
       System.out 
         .println("About to replace special chars....with..." 
           + newString); 

       search = search.replaceAll(oldString, newString); 
       String newSearch = new String(search.replaceAll(arr[i], 
         newString)); 
       System.out 
         .println("Search String after replaceAll is ------------->: " 
           + newSearch); 
       System.out.println("--------------" 
         + search.replaceAll(arr[i], newString) 
         + "---------------" + search); 

      } 
     } 

回答

0

您需要首先轉義單個反斜槓(在轉義其他任何東西之前),或者您可以雙重轉義一些反斜槓。

例子:1+1

更換+通過\+ =>1\+1

通過\\更換\ =>1\\+1(哎呀!)

0

不知道,如果你有你的答案。今天我正在嘗試相同的。我修改了你的代碼來使用我的解決方案。希望它對你有幫助。

String search = "$&+"; 

String[] arr = { "+", "-", "&&", "||", "!", "(", ")", "{", "}", "[", "]", "^", "\"", "~", "*", "?", ":", "\\", "AND", "OR" }; 

for (int i = 0; i < arr.length; i++) { 
System.out.println("arr[" + i + "]>>>>>>>>>>>>>>>" + arr[i]); 
System.out.println(search.contains((String) arr[i]) 
     + "---------->" + arr[i]); 

if (search.contains((String) arr[i])) { 
    System.out.println("..index..."+search.indexOf((String) arr[i])); 
    String oldString = (String) arr[i]; 
    System.out.println("check if it has old string" 
      + search.contains(oldString)); 
    String newString = new String("\\\\" + arr[i]); 
    System.out 
      .println("About to replace special chars....with..." 
        + newString); 

    search = search.replace("\\" + oldString, newString); 
    String newSearch = new String(search); 
    System.out 
      .println("Search String after replaceAll is ------------->: " 
        + newSearch); 

} 

}