簡體   English   中英

如何使用replaceAll方法將雙引號替換為“

[英]How to replace double quote with " using replaceAll method

我見過其他人也曾問過類似的問題,並遵循了給那些人的指示,但是我仍然無法使我的代碼正常運行。

try {

    FileReader fr_p = new FileReader("p.txt");
    BufferedReader in_p = new BufferedReader(fr_p);

    String line = in_p.readLine();

    for (;;) {

        line = line.replaceAll("&","&");
        line = line.replaceAll("<","&lt;");
        line = line.replaceAll(">","&gt;");
        line = line.replaceAll("\"","&quot;");

        people.add(line);
        line = in_p.readLine();
        if (line == null) break;

    }

    in_p.close();
} catch (FileNotFoundException e) {

    System.out.println("File p.txt not found.");
    System.exit(0);

} catch (IOException e) {

    System.out.println("Error reading from file.");
    System.exit(0);

}

這是我編寫的代碼,試圖將每個名稱放在文本文件的單獨一行中,然后將其放入ArrayList中,用其XML實體替換特殊字符。 然后,我稍后將其寫入HTML文件。

我編寫的代碼對前三個字符來說就可以了,但是當它到達試圖將任何雙引號更改為&quot; ,它不會改變他們,最終給我â€而不是一個雙引號的。 我不確定我應該對我的代碼進行哪些更改才能使其正常工作。

當我跑步

String line = "This is a string with \" and \" in it";
line = line.replaceAll("\"","&quot;");
System.out.println(line);

我懂了

This is a string with &quot; and &quot; in it

注意:引號有很多不同的種類,但只有一個"字符。如果引號不同,則不會匹配。

https://en.wikipedia.org/wiki/Quotation_mark

我的行為與您相同。 Java編譯器在引號'“'上占用了轉義字符。regex編譯器期望在輸入字符串文字時也希望對引號也進行轉義,這有些奇怪。不應該這樣,但是在這種情況下是。

如果您先准備一個逃脫的逃生通道,它將起作用。

   String lineout = line.replaceAll("\\\"","&quote;");

或者,您可以將String對象用於搜索表達式。

   String line = "embedded\"here";
   String searchstring = "\"";
   String lineout = line.replaceAll(searchstring,"&quote;");

我會把你的代碼改為這樣

line = line.replace("&","&amp;")
           .replace("<","&lt;")
           .replace(">","&gt;")
           .replace("\"","&quot;");

它應該像您的一樣工作,但無需使用regexp即可進行簡單替換。

您有編碼問題,可以通過設置其unicode代碼的單引號來解決:

line = line.replaceAll("\"", "\u0027");

用。。。來代替

 String replace = line.replace("&quot;", "''"); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM