读取包含空格的字符串值:Java

Read string value including spaces : Java

我需要从用冒号分隔的文件中读取 space 分隔值。

我的文件有这个数据-

Name : User123
DOB : 1/1/1780
Application Status : Not approved yet

当前实施:我正在将定界符(在我的例子中是冒号)之后的所有值复制到一个新文件,并相应地从新文件中读取值。

正在将条目复制到新文件时 spaces 被忽略。在上面的文件中,“尚未批准”仅保存为“未批准”。我怎样才能得到完整的线?这是我的代码 -

String regex = "\b(Name |DOB | Application Status )\s*:\s*(\S+)";
        
Pattern p = Pattern.compile(regex);
try (
        BufferedReader br = new BufferedReader(new FileReader("<file to read data>"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("<copy the new file here>"))) {
    String line;
          
    while ((line = br.readLine()) != null) {
        Matcher m = p.matcher(line);
        if (m.find())
            bw.write(m.group(2) + '\n');
    }
}
        
String st;
int count = -1;
String[] data = new String[100];
        
File datafile =new File("<new file where data is copied>");   
        
try {
    Scanner sc = new Scanner(datafile);

    while(sc.hasNextLine()) {
        data[++count] = sc.nextLine();
    }
} catch(Exception e) {
    System.out.println(e);
}

正则表达式 "\b(Name |DOB | Application Status )\s*:\s*(\S+)"; 中的 \S+ 仅获取非白色 space 字符。因此它在 "Not" 值后看到 space 后终止。为了在 ":" 之后获得全部值,将 \S+ 更改为 .*,这会获取除换行符之外的任何字符。所以正则表达式变成这样"\b(Name |DOB | Application Status )\s*:\s*(.*)"。它在值之后获取所有 space,因此 trim 使用它之前的值。所以你的代码变成这样

String regex = "\b(Name |DOB | Application Status )\s*:\s*(.*)";

Pattern p = Pattern.compile(regex);
try (BufferedReader br = new BufferedReader(new FileReader("<file to read data>"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("<copy the new file here>"))) 
{
    String line;
  
    while ((line = br.readLine()) != null) {
        Matcher m = p.matcher(line);
        if (m.find())
            bw.write(m.group(2) + '\n');
    }
}

String st;
int count = -1;
String[] data = new String[100];

File datafile =new File("<new file where data is copied>");   

try
{
    Scanner sc = new Scanner(datafile);
    while(sc.hasNextLine())
    {
        data[++count] = sc.nextLine().trim();
    }
}
catch(Exception e)
{
    System.out.println(e);
}