【问题标题】:How can i derive specific data from the string?如何从字符串中获取特定数据?
【发布时间】:2012-02-13 08:43:49
【问题描述】:

我有以下字符串,我想从 a href 标记中导出数字 (104321)。我怎样才能得出这个数字。

Hello this is testing string <a href=\"/testing/104321\">Ap</a><img src=\"Image Url" width=\"222\" height=\"149\"/><br/><br/>test\u00e4n p\u00e4\u00e4ll\u00e4 test, test\u00e4, test?

我希望最终的输出是这样的。

String[] strExample= {"testing", "104321","test\u00e4n p\u00e4\u00e4ll\u00e4 test, test\u00e4, test?"};

感谢任何帮助。

【问题讨论】:

    标签: java android string pattern-matching arrays


    【解决方案1】:

    您可以尝试使用正则表达式的简单模式匹配器:

    String THE_PATTERN = "<a\\s+href\\s*=\\s*\"/([a-zA-Z]+)/([0-9]+)";
    Matcher m = Pattern.compile(THE_PATTERN).matcher(THE_INPUT_STRING);
    String[] results = new String[2];
    if (m.find()) {
        results[0] = m.group(1);
        results[1] = m.group(2);
    }
    

    虽然没有尝试过,所以可能会有一些小/易于修复的错误。

    【讨论】:

    • 好的,但是自从我回答后你改变了你的问题(你添加了第三个字符串来匹配)。只需调整正则表达式,在要匹配的第三部分周围加上括号,m.group(3) 将返回它。查看Pattern javadoc 了解更多关于正则表达式和Matcher 的信息
    • 非常感谢。你能再帮帮我吗?我还想要
      标签之后的字符串。我也改变了我的问题。请看这个并给我解决方案。我一直很感谢你。
    • 我以前从没用过Pattern and Matcher,请你再帮我解决一下我的问题吗?
    • 是的,但我不知道变量。什么可能会改变,什么应该被修复?
    • 我需要图像标签关闭后和
      标签后的消息。
    【解决方案2】:

    对于单个案例

    String[] strExample = str.split("^.+?\\\"/|\\\\\">.+<br/>|/");
    

    会起作用。如果您要解析的字符串发生很大变化,它将中断。如果您需要考虑更多模式,可能会提供更多示例。

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 2010-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多