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

Java技术求助:从文本文件中提取Name与Age字段

Fixing Precise Extraction of Name and Age in Java

Hey there! Let's sort out your problem with extracting Name and Age values from that messy text file. Your current code just grabs everything from the last occurrence of "Name:" to the end of the line—this is why you're getting extra unwanted content instead of just the target values.

The Better Approach: Regular Expressions

Since your text follows a consistent pattern for Name and Age (Name: [YourName] Age: [YourAge] Years), regular expressions are perfect for pinpointing and capturing exactly what you need.

Improved Code

Here's the revised version of your class that extracts the values cleanly:

package myclass;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadFromFile2 {
    public static void main(String[] args)throws Exception {
        File file = new File("C:\\Users\\Ss\\Desktop\\s.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        
        // Define the regex pattern to match Name and Age
        Pattern pattern = Pattern.compile("Name:\\s*(.*?)\\s*Age:\\s*(\\d+)\\s*Years");
        
        while ((st = br.readLine()) != null) {
            Matcher matcher = pattern.matcher(st);
            // Check if the pattern exists in the current line
            if (matcher.find()) {
                String name = matcher.group(1); // Get the captured Name value
                String age = matcher.group(2);  // Get the captured Age value
                System.out.println("Name: " + name);
                System.out.println("Age: " + age);
            }
        }
        br.close(); // Don't forget to close the reader to avoid resource leaks!
    }
}

Let's Break Down the Regex

  • Name:\\s*: Matches the literal "Name:" followed by any number of whitespace characters (spaces, tabs, etc.)
  • (.*?): A non-greedy capture group that grabs all characters until it hits the next part of the pattern (this is your Name value)
  • \\s*Age:\\s*: Matches "Age:" surrounded by any whitespace
  • (\\d+): A capture group that grabs one or more digits (this is your Age value)
  • \\s*Years: Matches "Years" preceded by any whitespace

Key Notes

  • If your text has multiple Name/Age pairs per line, replace matcher.find() with a while (matcher.find()) loop to capture all of them
  • The regex handles extra spaces between labels and values, which is common in unstructured text
  • Always close your BufferedReader to free up system resources (added this step in the code above)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:57:48