【问题标题】:Java remove Sub-string that includes quotesJava删除包含引号的子字符串
【发布时间】:2011-10-02 18:27:10
【问题描述】:
    String strLine = "";

    try
    {
        BufferedReader b = new BufferedReader(new FileReader("html.txt"));
        strLine = b.readLine();
    } catch(Exception e)
    {
        e.printStackTrace();
    }   

    String[] temp = strLine.split("<");
    temp = temp[1].split(">");
    String temp1 = ("<"+temp[0]+">");

    strLine = strLine.replaceFirst(temp1,"");
    System.out.println(strLine);

基本上我想删除这个字符串

<span title="Representation in the International Phonetic Alphabet (IPA)" class="IPA"> 

来自包含

的文件
<span title="Representation in the International Phonetic Alphabet (IPA)" class="IPA">no'b?l</span> 

但是到目前为止,我的代码仅在字符串不包含引号时才有效。我该如何解决这个问题。我试过使用

.replaceAll("\\\"","\\\\\""); 

但还是失败了。

任何帮助或信息将不胜感激。

【问题讨论】:

标签: java string replace quotes


【解决方案1】:

您的问题是 replaceFirst 接受正则表达式,但您输入的是任意字符串,其中可能包含在正则表达式中具有特定含义的各种特殊字符。我不认为引号是你的问题,而是 问号 括号。

解决此问题的一种方法是使用String#replace 方法,该方法接受字符串而不是正则表达式。也就是说,使用以下行:

strLine = strLine.replace(temp1,"");

这与您的代码不同之处在于它替换了该行中 temp1 的所有实例,而不仅仅是第一个实例,但我认为您应该可以接受。

【讨论】:

  • 是的,谢谢,将 strLine.replaceAll 更改为 strLine.replace 解决了我的问题。
【解决方案2】:

如果您正确转义,AFAIK replaceAll("///"","/////""); 会起作用:转义字符是 \,而不是 /。尝试使用它。

【讨论】:

  • temp1 = temp1.replaceAll("\\\"","\\\\"");我试过这个但是它仍然不起作用。也许不是因为引号。
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多