0
  1. 假设输入字符串是 Abc def ghi.. 我希望结果像这样 Abc\def\ghi

    Date=122
    Shipper\ Id=11
    Bill\ No=54433
    Weight=431
    Shipper\ Last\ Name=aaa
    Shipper\ First\ Name=cdcx
    
4

6 回答 6

0

\不需要在替换字符串中转义,因此

output = input.replaceAll("(?=\\s)", "\\")

会成功的。

于 2014-09-05T07:38:56.770 回答
0

使用正则表达式replaceAll(字符串正则表达式,字符串替换)

\s匹配每个空白字符并+匹配前面的模式元素一次或多次。

所以请试试这个:

public static void main(String[] args){
        String s="Abc    def     ghi";
        String output = s.replaceAll("\\s+", "\\\\");
        System.out.println(output);// output :Abc\def\ghi
    }
于 2014-09-05T08:51:24.317 回答
0

你可以这样尝试:

string s = "Abc" + "\\"+ "def" + "\\" + "ghi";

或者你可以尝试" "\

string result  = s.replaceAll(" ","\\ ");
于 2014-09-05T06:06:36.827 回答
0
"Abc def ghi".replaceAll("(?=\\s)", "\\\\")
于 2014-09-05T06:08:57.720 回答
0

尝试这个

String s= " Abc def gh";
System.out.println(s.replace(" ", "\\ "));

编辑:

    String s = " Abc def gh";
    // System.out.println(s.replace(" ", "\\ "));

    File f = new File("trail.properties");
    f.createNewFile();
    FileWriter fileWriter = new FileWriter(f);

    fileWriter.write(s.replace(" ", "\\ "));

    fileWriter.close();

输出:

\ Abc\ def\ gh
于 2014-09-05T06:09:01.363 回答
0

使用正则表达式匹配所有空格\s和 prepend \
在替换模式中,您需要\使用另一个反斜杠来转义文字:\\

String result = searchText.replaceAll("(\\s)", "\\\$1");

于 2014-09-05T06:11:29.353 回答