【问题标题】:Logical help - java regex逻辑帮助 - java 正则表达式
【发布时间】:2013-04-25 18:42:38
【问题描述】:

我有一个包含图像标签的字符串,超过 1 个。现在我需要正则表达式输出 alt= 标签。我试过这样:

while (m3.find()) {
    Pattern p4 = Pattern.compile("<!\\[CDATA\\[(.*?)\\]\\]>");
    Matcher m4 = p4.matcher(m3.group());

    while (m4.find()) {
         if(m4.group().contains("<img src")) {
            Pattern p6 = Pattern.compile("<img src(.*?)/>");
        Matcher m6 = p6.matcher(m4.group());

        while (m6.find()) {
                Pattern p7 = Pattern.compile("alt=\"(.*?)\"");
                Matcher m7 = p7.matcher(m6.group());

            while (m7.find()) {
messages.add(m4.group().replace(m6.group(), m7.group().replace("alt=",  "").replace("\"", "")).replace("<![CDATA[", "").replace("]]>", ""));
                                } 
                            }
                        } else {
                            messages.add(m4.group().replace("<![CDATA[", "").replace("]]>", ""));
                        }
                    }
                }

问题是:图片标签不止1个。 messages 是一个 ArrayList。对于实际消息中的所有图像,我只需要 1 个messages.add。代码本身做了一些非常不同的事情,我不知道如何修复它或我的错误在哪里:/我只想用alt="..."的内容替换整个内容,但每个实际消息都包含。谁能帮帮我?

【问题讨论】:

    标签: java android regex logic


    【解决方案1】:

    也许您应该使用像jsoup 这样的第三方库,它允许以jquery 方式解析、提取和修改html 文档。使用这个库,改变某些 html 元素的属性(如explained here)应该像这样工作:

    Document doc = Jsoup.parse(html);
    doc.select("div.comments a").attr("rel", "nofollow");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 2011-06-10
      相关资源
      最近更新 更多