Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

regex - Replacing single '' with '\' in Java

How do I replace a single '' with '\'? When I run replaceAll() then I get this error message.

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

My code:

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

String.replaceAll(String,String) is regex.
String.replace(String,String) will do what you want.

The following...

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

Produces...

C:Documents and SettingsHUSAINMy DocumentsMy Palettes
C:\Documents and Settings\HUSAIN\My Documents\My Palettes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...