【发布时间】: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()?