【问题标题】:how to remove some words from a string in java如何从java中的字符串中删除一些单词
【发布时间】:2011-09-05 09:02:24
【问题描述】:

我在android平台上工作,我使用一个字符串变量来填充html内容,之后我想删除一些单词(特别是删除<head>..</head>标签之间的任何单词。有什么解决方案吗?

【问题讨论】:

    标签: java android string replace


    【解决方案1】:
    String newHtml = oldHtml.replaceFirst("(?s)(<head>)(.*?)(</head>)","$1$3");
    

    解释:

    oldHtml.replaceFirst(" // we want to match only one occurrance
    (?s)                   // we need to turn Pattern.DOTALL mode on
                           // (. matches everything, including line breaks)
    (<head>)               // match the start tag and store it in group $1
    (.*?)                  // put contents in group $2, .*? will match non-greedy,
                           // i.e. select the shortest possible match
    (</head>)              // match the end tag and store it in group $3
    ","$1$3");             // replace with contents of group $1 and $3
    

    【讨论】:

      【解决方案2】:

      另一种解决方案:)

      String s = "Start page <head> test </head>End Page";
      StringBuilder builder = new StringBuilder(s);
      builder.delete(s.indexOf("<head>") + 6, s.indexOf("</head>"));
      
      System.out.println(builder.toString());
      

      【讨论】:

        【解决方案3】:

        试试:

        String input = "...<head>..</head>...";
        String result = input.replaceAll("(?si)(.*<head>).*(</head>.*)","$1$2");
        

        【讨论】:

        • 如果内容包含换行符将不起作用(几乎可以肯定是这种情况)
        猜你喜欢
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-17
        • 1970-01-01
        • 1970-01-01
        • 2014-11-21
        相关资源
        最近更新 更多