【问题标题】:Read string value including spaces : Java读取包含空格的字符串值:Java
【发布时间】:2021-03-09 22:36:12
【问题描述】:

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

我的文件有这些数据 -

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

当前实现:我将分隔符(在我的情况下为冒号)之后的所有值复制到新文件并相应地从新文件中读取值。

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

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);
}

【问题讨论】:

  • 您的正则表达式 ((\\S*)) 不会捕获分隔符后的“所有值”,而只会捕获第一个单词。请改用(.*)。或者直接使用line.split("\\s*:\\s*")
  • String.split(":") 和一些String.trim()?

标签: java separator


【解决方案1】:

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2016-06-18
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    相关资源
    最近更新 更多