通过正则批量提取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.");
        }
    }
相关推荐
Fireworkitte6 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
weixin-a153003083166 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
DCTANT6 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.6 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
黄雪超7 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice7 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变7 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
lijingguang7 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented8 小时前
【C#中路径相关的概念】
开发语言·c#
CoderCodingNo8 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法