string.replaceAll的问题

时间:2012-11-02 08:43:32

标签: java

我只是想用\\

替换字符串\\\\

以下是程序,但它正在终止

String path="\\dctmadmin\\Human Resource\\Training\\Procedures\\Formalities\\Legalities\\Material";         

long start = System.currentTimeMillis();
// replace this string \\ with \\\\
String formatedPath = path.replaceAll("\\\\", "\\\\\\\\");
System.out.println(" string after formatting using replaceAll = "+formatedPath);
long end = System.currentTimeMillis();
System.out.println(" time take in milli seconds for String.replaceAll = "+Long.toString(end-start) );

请让我知道我正在做的错误。

6 个答案:

答案 0 :(得分:3)

对于不需要正则表达式功能的文字字符串替换,您应该使用replace而不是replaceAll,因为它更简单,更有效。

// replace single backslash with double
String formatedPath = path.replace("\\", "\\\\");

答案 1 :(得分:1)

您的真实字符串只包含一个\。测试

System.out.println("\\dctmadmin\\Human Resource\\Training\\Procedures\\Formalities\\Legalities\\Material");

所以你的replaceAll运行正常,如果它在System.out.println("你的字符串" .replaceAll(...));

时返回double \\

答案 2 :(得分:1)

尝试

String path = 
    "\\dctmadmin\\Human Resource\\Training\\Procedures\\Formalities\\Legalities\\Material";


long start = System.currentTimeMillis();
// replace this string \\ with \\\\

String formatedPath = path.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");

System.out.println(" string after formatting using replaceAll = " + 
                   formatedPath);


long end = System.currentTimeMillis();

System.out.println(" time take in milli seconds for String.replaceAll = " + Long.toString(end - start));

System.out.println(" path  "+formatedPath);

答案 3 :(得分:0)

在你的字符串中,当你说\它实际意味着\由另一个\转义时,它正在正确地替换它。

String path="\\dctmadmin\\Human Resource\\Training\\Procedures\\Formalities\\Legalities\\Material";

         System.out.println("String before: "+ path);
        long start = System.currentTimeMillis();
        // replace this string \\ with \\\\

          String formatedPath = path.replaceAll("\\\\", "\\\\\\\\");

          System.out.println(" string after formatting using replaceAll = "+formatedPath);

输出我

   String before:  \dctmadmin\Human Resource\Training\Procedures\Formalities\Legalities\Material

     string after formatting using replaceAll = \\dctmadmin\\Human Resource\\Training\\Procedures\\Formalities\\Legalities\\Material
     time take in milli seconds for String.replaceAll = 2

答案 4 :(得分:0)

你没事。 在Java中,字符串\\代表一个反斜杠,在正则表达式中它是非String转义。

    String formatedPath = path.replaceAll("\\\\", "\\\\\\\\");
    System.out.println("path         = " + path);
    System.out.println("formatedPath = " + formatedPath);

给出

path         = \dctmadmin\Human Resource\Training\Pr...s\Form...s\L...s\Material
formatedPath = \\dctmadmin\\Human Resource\\Training\\Pr..s\\Form...s\\Material

答案 5 :(得分:0)

的输出
string after formatting using replaceAll = \\dctmadmin\\Human Resource\\Training\\Procedures\\Formalities\\Legalities\\Material

是对的。看起来它没有改变,因为你正在贬低你的原文中的'\'被转义的事实:)