2017-04-26 57 views
0

我使用這個正則表達式我是一個簡單的方法主要測試了它從我的字符串SVG .replaceAll("\\{", "{")刪除所有逃生符號的所有逃生的符號,當我試圖把它工作正常取下字符串SVG JAVA

System.out.println("<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" class=\"highcharts-root\" style=\"font-family:&quot;lucida grande&quot;, &quot;lucida sans unicode&quot;, arial, helvetica, sans-serif;font-size:12px;\" xmlns=\"http://www.w3.org/2000/svg\" width=\"600\" height=\"350\"><desc>Created" 
     + " with Highcharts 5.0.7</desc><defs><clipPath id=\"highcharts-lqrco8y-45\"><rect x=\"0\" y=\"0\" width=\"580\" height=".replaceAll("\\{", "{")); 

在我的代碼中使用這個沒有例外,但替換所有函數似乎沒有工作。

@RequestMapping(value = URL, method = RequestMethod.POST) 
public String svg(@RequestBody String svg) throws TranscoderException, IOException { 

    String result = svg; 

    String passStr = (String) result.subSequence(5, result.length() - 2); 

    passStr = passStr.replaceAll("\\{", "{"); 

    InputStream is = new ByteArrayInputStream(Charset.forName("UTF-8").encode(passStr).array()); 
    service.converter(is); 

    return result; 
} 
+0

如果要解析XML,請使用XML解析器。 –

回答

0

試試這樣說:

public static void main(String[] args) { 
    String test = "abc\\{}def"; 
    System.out.println("before: " + test); 
    System.out.println("after: " + test.replaceAll("\\\\[{]", "{")); 
} 

輸出

before: abc\{}def 
after: abc{}def 
+0

與以前的正則表達式相同。我不明白爲什麼它只有當我在主要方法中啓動它時才起作用,但是當我在代碼中使用它時,正則表達式不起作用。 – RockOrDead

+0

是的,我注意到了,我試過你的解決方案,但又一次。它適用於當我在主要方法中使用它,但不在我的應用程序中,如我的第一篇文章中所示。 – RockOrDead

+0

passStr = passStr.replaceAll(「\\\\ [{]」,「{」); System.out.println(passStr); 在此行中我看到,有呼叫後的replaceAll方法沒有變化。不知道爲什麼?!? – RockOrDead

0

你的第一個例子中沒有任何 「{」 字符,所以我並不感到驚訝它的工作原理(??)。

但無論如何,你的正則表達式是錯誤的。正則表達式中的反斜槓在Java字符串中均爲轉義字符。所以\\中的一個字符串就意味着\。這意味着你的正則表達式實際上只是\{,這意味着{。因此,您所做的只是將{替換爲{

如果你想一個正則表達式與{取代\{,你需要加倍每對正則表達式的反斜槓字符:\\\\{