通过正则批量提取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.");
        }
    }
相关推荐
潼心1412o14 分钟前
C++初阶(长期更新)第6讲:类和对象(下)
开发语言·c++·算法
wangbing112540 分钟前
使用jps jstack排查系统问题
java
夜晚回家42 分钟前
Python 零基础入门 | 输入的数字为什么不能直接算
开发语言·python
时间的拾荒人43 分钟前
Qt 事件机制全解析:从事件处理到事件过滤器
开发语言·qt·面试
于指尖飞舞1 小时前
java面试题总结
java·开发语言
ZealSinger1 小时前
LangChain4j用AiServices拼Tool
java·rag·ai智能体·langchain4j
vx_Biye_Design1 小时前
springboot高校选课系统82776-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·spring·课程设计·express
zhangzeyuaaa2 小时前
深入理解 Ruby 运算符:本质、分类、坑点与重载实战
开发语言·前端·ruby
一木 之林2 小时前
DeepSeek Agent 开发(一)
开发语言·前端·javascript
朔北之忘 Clancy2 小时前
青少年软编等考七级题解目录
开发语言·c++·青少年编程·gesp·csp·信奥赛·noi