通过正则批量提取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.");
        }
    }
相关推荐
lsx2024061 小时前
React 事件处理
开发语言
JQLvopkk2 小时前
能用C#开发AI
开发语言·人工智能·c#
郝学胜-神的一滴3 小时前
当AI遇见架构:Vibe Coding时代的设计模式复兴
开发语言·数据结构·人工智能·算法·设计模式·架构
阿里嘎多学长7 小时前
2026-02-16 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Frostnova丶8 小时前
LeetCode 190.颠倒二进制位
java·算法·leetcode
闻哥9 小时前
Redis事务详解
java·数据库·spring boot·redis·缓存·面试
hrhcode9 小时前
【Netty】五.ByteBuf内存管理深度剖析
java·后端·spring·springboot·netty
啊吧怪不啊吧9 小时前
C++之基于正倒排索引的Boost搜索引擎项目usuallytool部分代码及详解
开发语言·c++·搜索引擎·项目
道亦无名9 小时前
aiPbMgrSendAck
java·网络·数据库
CeshirenTester9 小时前
9B 上端侧:多模态实时对话,难点其实在“流”
开发语言·人工智能·python·prompt·测试用例