繁体   English   中英

Java正则表达式从html中删除标签

[英]Java Regular Expression to Remove tags from html

<table><tr><td>HEADER</td><td>Header Value <supporting value></td></tr><tr><td>SUB</td><td>sub value. write to <test@gmail.com></td></tr><tr><td>START DATE</td><td>11/23/ 2016</td></tr><tr><td>END DATE</td><td>11/23/2016</td></tr></table>

上面的文本是我的 html 字符串,需要提取 HEADER、SUB、START DATE 和 END DATE 的值。 我使用 Jsoup 来提取值,但我遇到了非 html 元素标签的问题。 API 要么跳过这些元素,要么添加一个最初不存在的结束标记。

所以我的想法是用&lt;替换非 html 元素标签&lt; 然后使用 Jsooup 提取值

有什么建议??

您可能希望参考jSoup来解析 HTML 文档。 您可以使用此 api 提取和操作数据。

您可以使用此正则表达式提取内容:

/<td>[^<]*<([^>]*)><\/td>/

假设标记布局看起来总是一样的。

虽然你不能使用正则表达式解析一个完整的 HTML 文档,因为它不是一种上下文无关的语言,实际上像这样的部分提取可能的。

找到解决方案,使用模式 <([^\\s>/]+) 从 html 字符串中获取所有标签

然后用“&lt”“&gt”替换除TR和TD之外的所有标签。 当我使用 Jsoup 解析文本时,我得到了所需的值。

请找到下面的代码,

public class JsoupParser2 {

public static void main(String args[]) {

    String orginalString, replaceString = null;
    HashSet<String> tagSet = new HashSet<String>();
    HashMap<String,String> notes = new HashMap<String,String>();

    Document document = null;
    try{

        //Read the html content as String
        File testFile = new File("C:\\test.html");
        List<String> content = Files.readLines(testFile,  Charsets.UTF_8);
        String testContent = content.get(0);

        //Get all the tags present in the html content
        Pattern p = Pattern.compile("<([^\\s>/]+)");
        Matcher m = p.matcher(testContent);
        while(m.find()) {
            String tag = m.group(1);
            tagSet.add(tag);
        }

        //Replace the tags thats non-html
        for(String replaceTag : tagSet){
            if(!"table".equals(replaceTag) && !"tr".equals(replaceTag) && !"td".equals(replaceTag)){
                orginalString = "<"+replaceTag+">";
                replaceString = "&lt;"+replaceTag+"&gt;";
                testContent = testContent.replaceAll(orginalString, replaceString);
            }
        }

        //Parse the html content
        document = Jsoup.parse(testContent, "", Parser.xmlParser());

        //traverse through TR and TD to get to the values
        //store the values in the map
        Elements pTags = document.select("tr");
        for (Element tag : pTags) {
            if(!tag.getElementsByTag("td").isEmpty()){
                String key = tag.getElementsByTag("td").get(0).text().trim();
                String value = tag.getElementsByTag("td").get(1).html().trim();
                System.out.println("KEY : "+key); System.out.println("VALUE : "+value);
                notes.put(key, value);
                System.out.println("==============================================");
            }
        } 

    }catch (IOException e) {
        e.printStackTrace();
    }catch(IndexOutOfBoundsException ioobe){
        System.out.println("ioobe");
    }
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM