2013-01-06 35 views
10

Làm cách nào để thay thế một đơn '\' bằng '\\'? Khi tôi chạy replaceAll() thì tôi nhận được thông báo lỗi này.Thay thế đơn '' bằng '\' trong Java

Exception in thread "main" java.util.regex.PatternSyntaxException: 
          Unexpected internal error near index 1 \ 
                   ^
    at java.util.regex.Pattern.error(Pattern.java:1713) 
    at java.util.regex.Pattern.compile(Pattern.java:1466) 
    at java.util.regex.Pattern.<init>(Pattern.java:1133) 
    at java.util.regex.Pattern.compile(Pattern.java:823) 
    at java.lang.String.replaceAll(String.java:2190) 
    at NewClass.main(NewClass.java:13) 
Java Result: 1 

Mã của tôi:

public class NewClass { 
    public static void main(String[] args) { 
     String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes"; 
     str = str.replaceAll("\\", "\\\\"); 
     System.out.println(str); 
    } 
} 
+0

cố gắng thay thế 'str = str.replaceAll (" \\ "," \\\\ ")' bởi '' str = str.replaceAll ("^ \\ $", "^\\\\ $ "); ' – Billie

+0

Ý của bạn là gì, thay thế đơn '\' bằng '\'? Âm thanh như một cái noop. –

+0

có thể trùng lặp của [vấn đề Backslash với String.replaceAll] (http://stackoverflow.com/questions/1701839/backslash-problem-with-string-replaceall) – jlordo

Trả lời

18

String.replaceAll(String,String) là regex.
String.replace(String,String) sẽ thực hiện những gì bạn muốn.

Sau đây ...

String str = "C:\\Documents and Settings\\HUSAIN\\My Documents\\My Palettes"; 
System.out.println(str); 
str = str.replace("\\", "\\\\"); 
System.out.println(str); 

Tạo ...

C: \ Documents and Settings \ Husain \ My Documents \ My Palettes
C: \\ Documents and Settings \ \ HUSAIN \\ Tài liệu của tôi \\ My Palettes

9

\ cũng là một nhân vật đặc biệt trong regexp. Đây là lý do tại sao bạn nên làm một cái gì đó như thế này:

str = str.replaceAll("\\\\", "\\\\\\\\"); 
4

Bạn cần phải đầu tiên scape các \ cho chuỗi và sau đó scape nó cho regex, nó sẽ là \\\\ cho mỗi dấu gạch chéo.

1

Trong chuỗi ký tự, \ phải được thoát vớikhác. Và trong một chế độ, \ cũng phải được thoát bởi một số khác \\. Vì vậy, bạn phải thoát khỏi mỗi \ bốn lần: \\\\.

Cách khác là sử dụng Pattern.quote("\\") (đối với regex) và Matcher.quoteReplacement("\\\\") cho chuỗi thay thế.

0

Bạn có thể sử dụng Pattern.quote để làm cho nó dễ dàng hơn cho bạn để thoát khỏi giá trị, chẳng hạn như:

str = str.replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\")); 

hay, bạn chỉ có thể sử dụng String.replace:

str = str.replace("\\", "\\\\"); 

Xem: Pattern.quote, String.replaceMatcher.quoteReplacement

0

tệpPath = filePath.replaceAll (Matcher.quoteReplacement ("\"), Matcher.quoteReplacement ("\\ "));

Điều này hoạt động hoàn hảo. filePath = C: \ abc \

Các vấn đề liên quan