You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java读取文件行中花括号{}间内容并存储到变量?

问题描述

我现在能逐行读取BibTeX文件,但不知道怎么提取每行中{和}之间的文本并保存到不同变量里。文件格式如下:

@ARTICLE{
8249726, 
author={N. Khlif and A. Masmoudi and F. Kammoun and N. Masmoudi}, 
journal={IET Image Processing}, 
title={Secure chaotic dual encryption scheme for H.264/AVC video conferencing protection}, 
number={1}, 
year={2018}, 
volume={12}, 
pages={42-52}, 
keywords={adaptive codes;chaotic communication;cryptography;data compression;data protection;variable length codes;video coding;H.264/AVC video conferencing protection;advanced video coding protection;chaos-based crypto-compression scheme;compression ratio;context adaptive variable length coding;decision module;format compliance;inter-prediction encryption;intra-prediction encryption;piecewise linear chaotic maps;pseudorandom bit generators;secure chaotic dual encryption scheme;selective encryption approach;video compression standards}, 
doi={10.1049/iet-ipr.2017.0022}, 
ISSN={1751-9659}, 
month={Dec},
}

目前的代码只能读取整行:

public static void main(String[] args) {
    try {
        File myFile = new File("Latex3.bib");
        Scanner reader = new Scanner(myFile);
        while(reader.hasNextLine()) {
            System.out.println(reader.nextLine());
        }
    }catch(FileNotFoundException e) {
        e.getMessage();
    }   
}
解决方案

方法1:正则表达式匹配(推荐)

用正则表达式匹配每行中{和}之间的内容,同时提取前面的键名(比如author、title)。正则(.*?)=\{(.*?)\}可以匹配key={value}的结构,开头的@ARTICLE{后的ID单独处理。

修改后的代码示例:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BibReader {
    public static void main(String[] args) {
        // 用Map存储提取的键值对,方便后续调用
        Map<String, String> bibData = new HashMap<>();
        Pattern fieldPattern = Pattern.compile("(.*?)\\=\\{(.*?)\\}");
        Pattern idPattern = Pattern.compile("@ARTICLE\\{\\s*(.*?),");

        try {
            File myFile = new File("Latex3.bib");
            Scanner reader = new Scanner(myFile);
            
            while (reader.hasNextLine()) {
                String line = reader.nextLine().trim();
                if (line.isEmpty()) continue;

                // 处理文章ID
                if (line.startsWith("@ARTICLE{")) {
                    Matcher idMatcher = idPattern.matcher(line);
                    if (idMatcher.find()) {
                        bibData.put("id", idMatcher.group(1).trim());
                    }
                    continue;
                }

                // 处理其他字段
                Matcher fieldMatcher = fieldPattern.matcher(line);
                if (fieldMatcher.find()) {
                    String key = fieldMatcher.group(1).trim();
                    String value = fieldMatcher.group(2).trim();
                    // 移除值末尾可能存在的逗号
                    if (value.endsWith(",")) {
                        value = value.substring(0, value.length() - 1).trim();
                    }
                    bibData.put(key, value);
                }
            }

            // 打印提取结果,也可直接赋值给单独变量
            System.out.println("文章ID: " + bibData.get("id"));
            System.out.println("作者: " + bibData.get("author"));
            System.out.println("标题: " + bibData.get("title"));
            // 其他字段同理调用

        } catch (FileNotFoundException e) {
            System.err.println("文件未找到: " + e.getMessage());
        }
    }
}

方法2:字符串索引定位

如果不想用正则,也可以通过indexOf找到{和}的位置,直接截取字符串:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class BibReader {
    public static void main(String[] args) {
        String id = "";
        String author = "";
        String title = "";
        // 按需定义需要的变量

        try {
            File myFile = new File("Latex3.bib");
            Scanner reader = new Scanner(myFile);
            
            while (reader.hasNextLine()) {
                String line = reader.nextLine().trim();
                if (line.isEmpty()) continue;

                // 处理文章ID
                if (line.startsWith("@ARTICLE{")) {
                    int start = line.indexOf("{") + 1;
                    int end = line.indexOf(",");
                    if (start != -1 && end != -1) {
                        id = line.substring(start, end).trim();
                    }
                    continue;
                }

                // 提取花括号内的内容
                int braceStart = line.indexOf("{");
                int braceEnd = line.indexOf("}");
                if (braceStart != -1 && braceEnd != -1) {
                    String value = line.substring(braceStart + 1, braceEnd).trim();
                    // 根据行开头的键名赋值给对应变量
                    if (line.startsWith("author=")) {
                        author = value;
                    } else if (line.startsWith("title=")) {
                        title = value;
                    }
                    // 其他字段同理判断赋值
                }
            }

            // 打印结果
            System.out.println("ID: " + id);
            System.out.println("作者: " + author);
            System.out.println("标题: " + title);

        } catch (FileNotFoundException e) {
            System.err.println("文件未找到: " + e.getMessage());
        }
    }
}

注意事项

  • 如果BibTeX文件存在字段跨多行的情况(比如作者列表换行),上述逐行处理会失效,这种场景需要先读取整个条目再统一解析。
  • 务必处理字段值末尾的逗号,避免残留符号影响后续使用。

内容的提问来源于stack exchange,提问作者Anas Aaquil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 06:50:50