通过正则批量提取PDF中文本信息

通过正则批量提取PDF中文本信息

复制代码
public static void main(String[] args) throws IOException {
        // 这是预设的正则,可以通过预设不同的正则提取不同内容(电话号码、邮箱等等)
        String[] options = {"([0-9]{6}.+,00)", "待设定(正则)", "待设定(正则)"};
        // 选项弹窗
        int selectedOption = JOptionPane.showOptionDialog(null, "请选择一个选项", "选项框", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        // 获取选项值
        String selectedValue = "";
        if (selectedOption != JOptionPane.CLOSED_OPTION) {
            selectedValue = options[selectedOption];
        } else {
            // 如果没有选择,则可以手动输入正则
            selectedValue = JOptionPane.showInputDialog(null, "请输入您的文本:","([0-9]{6}.+,00)");
        }

        // 通过文件选择器选择pdf文件
        JFileChooser chooser = new JFileChooser();
        // 过滤pdf文件
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Files", "pdf");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            // 根据选择的文件获取pdf文本
            File selectedFile = chooser.getSelectedFile();
            PDDocument document = PDDocument.load(new File(selectedFile.getPath()));
            PDFTextStripper stripper = new PDFTextStripper();
            String text = stripper.getText(document);

            // 通过正则从文本中获取内容
            Pattern pattern = Pattern.compile(selectedValue);
            Matcher matcher = pattern.matcher(text);
            String fileName = new File(selectedFile.getPath()).getName();

            // 将提取的内容写入文件
            String outputFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".txt";
            FileWriter writer = new FileWriter(outputFileName);
            while (matcher.find()) {
                String group = matcher.group();
                writer.write(group);
                writer.write("\n");
            }
            writer.close();
            document.close();
        } else {
            // TODO 换成提示框
            System.out.println("File selection cancelled.");
        }
    }
相关推荐
宠友信息1 分钟前
资源权限与钱包流水在即时通讯源码后端架构中的设计
java·spring boot·redis·websocket·缓存
不知名的老吴2 分钟前
浅谈:编程语言中的那些「锁」事(二)
java·开发语言
程序员小八7775 分钟前
AOP 切面
java
地铁潜行者18 分钟前
从单体思维到微服务:服务拆分与组件选型实践
java·后端
花生了什么事o19 分钟前
线程池参数调优:corePoolSize 怎么设置
java·后端
灵性(๑>ڡ<)☆20 分钟前
Java学习笔记 --面向对象进阶
java·笔记·学习
写了20年代码的老程序员30 分钟前
Java Lambda 类型安全查询是怎么实现的?从字节码层面拆一遍
java·开源
唐青枫42 分钟前
Java RabbitMQ 实战指南:从交换机、队列到可靠消息处理
java
卓怡学长1 小时前
w272基于springboot便民医疗服务小程序
java·spring boot·spring·小程序·intellij-idea
一方~1 小时前
权限系统设计
java