JEditorPaneHTMLEditorKitParserMethodPatternMatching模式匹配

wen java案例 1

本文目录导读:

JEditorPaneHTMLEditorKitParserMethodPatternMatching模式匹配

  1. 核心组件
  2. 模式匹配方法
  3. 高级模式匹配示例
  4. 使用模式匹配的实用函数
  5. 关键要点

我来详细解释一下 JEditorPane、HTMLEditorKit 中的解析器方法模式匹配。

核心组件

JEditorPane

JEditorPane editor = new JEditorPane();
editor.setContentType("text/html");
editor.setText("<html><body><p>Hello World</p></body></html>");

HTMLEditorKit

HTMLEditorKit kit = new HTMLEditorKit();
editor.setEditorKit(kit);

解析器相关类

  • HTMLEditorKit.Parser
  • HTMLEditorKit.ParserCallback

模式匹配方法

基本解析器模式匹配示例

import javax.swing.text.html.parser.*;
import javax.swing.text.html.*;
import javax.swing.text.*;
import java.io.*;
public class HTMLParserPattern {
    public static void main(String[] args) {
        String html = "<html><body>" +
                      "<h1>标题</h1>" +
                      "<p>段落文本</p>" +
                      "<a href='http://example.com'>链接</a>" +
                      "<img src='image.jpg' alt='图片'/>" +
                      "</body></html>";
        try {
            // 方法1: 使用HTMLEditorKit的解析器
            parseWithHTMLEditorKit(html);
            // 方法2: 使用ParserDelegator
            parseWithParserDelegator(html);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 方法1: HTMLEditorKit方式
    static void parseWithHTMLEditorKit(String html) throws Exception {
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLEditorKit.Parser parser = kit.getParser();
        StringReader reader = new StringReader(html);
        parser.parse(reader, new HTMLEditorKit.ParserCallback() {
            @Override
            public void handleText(char[] data, int pos) {
                String text = new String(data);
                System.out.println("文本: " + text);
                // 模式匹配示例
                if (text.matches(".*标题.*")) {
                    System.out.println("  -> 匹配标题模式");
                }
                if (text.contains("段落")) {
                    System.out.println("  -> 包含段落关键词");
                }
            }
            @Override
            public void handleStartTag(HTML.Tag tag, MutableAttributeSet attrs, int pos) {
                System.out.println("开始标签: " + tag);
                // 标签模式匹配
                if (tag == HTML.Tag.A) {
                    String href = (String) attrs.getAttribute(HTML.Attribute.HREF);
                    if (href != null && href.matches("https?://.*")) {
                        System.out.println("  -> 匹配URL模式: " + href);
                    }
                }
                if (tag == HTML.Tag.IMG) {
                    String src = (String) attrs.getAttribute(HTML.Attribute.SRC);
                    if (src != null && src.matches(".*\\.(jpg|png|gif)$")) {
                        System.out.println("  -> 匹配图片路径模式: " + src);
                    }
                }
            }
        }, false);
    }
    // 方法2: ParserDelegator方式
    static void parseWithParserDelegator(String html) throws Exception {
        ParserDelegator parser = new ParserDelegator();
        StringReader reader = new StringReader(html);
        parser.parse(reader, new ParserDelegator.HTMLParserCallback() {
            @Override
            public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attrs, int pos) {
                System.out.println("自闭合标签: " + tag);
                // 模式匹配
                if (tag == HTML.Tag.IMG) {
                    String alt = (String) attrs.getAttribute(HTML.Attribute.ALT);
                    if (alt != null && !alt.isEmpty()) {
                        System.out.println("  -> 图片描述: " + alt);
                    }
                }
            }
        }, true);
    }
}

高级模式匹配示例

正则表达式模式匹配

public class RegexPatternMatcher {
    // 匹配HTML标签
    private static final Pattern TAG_PATTERN = 
        Pattern.compile("<([a-zA-Z]+)[^>]*>");
    // 匹配属性
    private static final Pattern ATTRIBUTE_PATTERN = 
        Pattern.compile("(\\w+)=[\"']?([^\"'>]+)[\"']?");
    // 匹配URL
    private static final Pattern URL_PATTERN = 
        Pattern.compile("https?://[^\\s\"'<>]+");
    public static void matchPatterns(String html) {
        // 标签匹配
        Matcher tagMatcher = TAG_PATTERN.matcher(html);
        while (tagMatcher.find()) {
            System.out.println("发现标签: " + tagMatcher.group(1));
        }
        // 属性匹配
        Matcher attrMatcher = ATTRIBUTE_PATTERN.matcher(html);
        while (attrMatcher.find()) {
            System.out.println("属性: " + attrMatcher.group(1) + 
                             " = " + attrMatcher.group(2));
        }
    }
}

自定义回调模式匹配

class CustomPatternMatcher extends HTMLEditorKit.ParserCallback {
    // 模式匹配规则
    private List<PatternRule> rules = new ArrayList<>();
    public CustomPatternMatcher() {
        // 定义匹配规则
        rules.add(new PatternRule("标题", PatternType.TEXT_MATCH));
        rules.add(new PatternRule("https?://", PatternType.URL_MATCH));
        rules.add(new PatternRule("\\d{4}-\\d{2}-\\d{2}", PatternType.DATE_MATCH));
    }
    @Override
    public void handleText(char[] data, int pos) {
        String text = new String(data);
        for (PatternRule rule : rules) {
            if (rule.matches(text)) {
                System.out.println("匹配规则 '" + rule.pattern + "': " + text);
            }
        }
    }
    @Override
    public void handleStartTag(HTML.Tag tag, MutableAttributeSet attrs, int pos) {
        if (tag == HTML.Tag.A) {
            String href = (String) attrs.getAttribute(HTML.Attribute.HREF);
            if (href != null && href.startsWith("http")) {
                System.out.println("外部链接: " + href);
            }
        }
    }
    // 模式规则内部类
    static class PatternRule {
        String pattern;
        PatternType type;
        PatternRule(String pattern, PatternType type) {
            this.pattern = pattern;
            this.type = type;
        }
        boolean matches(String text) {
            switch (type) {
                case TEXT_MATCH:
                    return text.contains(pattern);
                case URL_MATCH:
                    return text.matches(pattern + ".*");
                case DATE_MATCH:
                    return text.matches(pattern);
                default:
                    return false;
            }
        }
    }
    enum PatternType {
        TEXT_MATCH,
        URL_MATCH,
        DATE_MATCH
    }
}

使用模式匹配的实用函数

public class HTMLPatternUtils {
    // 提取所有链接
    public static List<String> extractLinks(String html) {
        List<String> links = new ArrayList<>();
        Pattern linkPattern = Pattern.compile(
            "<a\\s+[^>]*href=[\"']([^\"']+)[\"'][^>]*>"
        );
        Matcher matcher = linkPattern.matcher(html);
        while (matcher.find()) {
            links.add(matcher.group(1));
        }
        return links;
    }
    // 提取所有图片
    public static List<String> extractImages(String html) {
        List<String> images = new ArrayList<>();
        Pattern imgPattern = Pattern.compile(
            "<img\\s+[^>]*src=[\"']([^\"']+)[\"'][^>]*>"
        );
        Matcher matcher = imgPattern.matcher(html);
        while (matcher.find()) {
            images.add(matcher.group(1));
        }
        return images;
    }
    // 清理HTML标签
    public static String stripHTML(String html) {
        return html.replaceAll("<[^>]*>", "")
                   .replaceAll("\\s+", " ")
                   .trim();
    }
    // 检查特定模式
    public static boolean containsPattern(String html, String pattern) {
        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(html);
        return m.find();
    }
}

关键要点

  1. 解析器选择

    • HTMLEditorKit.Parser - 用于Swing组件
    • ParserDelegator - 更灵活的解析方式
  2. 模式匹配方法

    • 字符串匹配 (contains, matches)
    • 正则表达式匹配
    • 标签属性匹配
  3. 回调处理

    • handleText() - 处理文本内容
    • handleStartTag() - 处理开始标签
    • handleEndTag() - 处理结束标签
    • handleSimpleTag() - 处理自闭合标签

这个框架提供了强大的HTML解析和模式匹配能力,可以根据需求实现复杂的HTML内容分析和处理。

抱歉,评论功能暂时关闭!