【问题标题】:Remove a part of string via first and last character?通过第一个和最后一个字符删除部分字符串?
【发布时间】:2012-05-13 19:00:27
【问题描述】:

由于查询远程 XML 提要,我得到一个 HTML 字符串。我使用结果将文本设置为TextView。问题是字符串包含TextView 元素不支持的HTML 注释标签。

现在,我需要一种方法来删除(子字符串)结果字符串,方法是指示将被删除的部分。我不能通过开始和结束位置工作,但我必须使用开始和结束字符串模式(<!-- 作为开始,--> 作为结束)。

我该怎么做?

【问题讨论】:

  • 发布您的代码,它可能有助于解决您的问题
  • @DaUltimateTrooper 在 HTML/XML 上使用正则表达式时要小心,只有在某些特殊情况下,它们才是正确的工具(尽管这可能是一个)。通常你应该使用 HTML/XML 解析器。
  • @Aerrow 什么代码?这是我描述的字符串:)。

标签: java android string


【解决方案1】:

你可以使用正则表达式,例如

    String input = "<!-- \nto be removed -->hello <!-- to be removed-->world";
    Pattern pattern = Pattern.compile("<!--.*?-->", Pattern.DOTALL | Pattern.UNICODE_CASE | Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(input);
    StringBuilder builder = new StringBuilder();
    int lastIndex = 0;
    while (matcher.find()) {
        builder.append(input.substring(lastIndex, matcher.start()));
        lastIndex = matcher.end();
    }
    builder.append(input.substring(lastIndex));
    System.out.println(builder);

【讨论】:

    【解决方案2】:

    我在这里找到了这个。我相信,由于 android 在这里是一个标签,所以答案将是相关的。

    android.text.Html.fromHtml(instruction).toString()
    

    Remove HTML tags from a String.

    【讨论】:

    • +1 用于在我之前发布。不过,您实际上并不需要 toString()
    • 我刚刚从下面的链接中复制了答案;)。我想它是为了以防万一!
    • 感谢您的建议。但我不想删除 HTML。只是 cmets 标签
    【解决方案3】:

    也许用这个:

    String str = "your html string";
    int start = str.indexOf("<!--");
    int end = str.indexOf("-->");
    str = str.replace(str.substring(start, (end - start)), "");
    

    【讨论】:

    • 更好用int end = str.lastIndexOf("--&gt;");
    • 不,我不这么认为。因为你永远不知道 html 里面是否有几个 cmets。
    • @Waqas 我指出它是因为我认为可能有嵌套的 cmets, but I see it's not legal in valid HTMLs。而且我并没有考虑打开一条评论,关闭它并打开(和关闭)另一条评论。
    • @Waqas 此代码删除了除每个结尾“-->”之外的所有内容。如果我尝试添加 + 1 结束,则应用程序崩溃。
    • 嗯...你试过这个吗?现在它返回另一个字符串ref; --&gt;
    【解决方案4】:

    你也可以使用HTML.fromHTML

    【讨论】:

    【解决方案5】:

    您可以使用Html.fromHtml() 方法在TextView 中使用html 格式的文本,例如:

    CharSequence text = Html.fromHtml("before <!--comment--><b>after</b>");
    myTextView.setText(text);
    

    TextView 现在将有文本“之前之后”。

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      • 2013-12-12
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多