[英]Read text from text file and display it line by line with the name of the field and its value
I have this text file:我有这个文本文件:
1 Juan García12-11-2016 Reparación caldera 110.50
2 Eva Blasco05-10-2016 Fuga de agua 200.00
3 Rosa Carreras23-01-2016 Cambio de filtro 0.75
And I need to display it like this on the console:我需要在控制台上像这样显示它:
Code: 1, Client: Juan García, Date: 12-11-2016, Concept: Reparación caldera, Price: 110.50
I have tried to do it with regex but i usually get errors and i don't have time to properly learn it我试过用正则表达式来做,但我通常会出错,而且我没有时间正确学习它
Pattern p = Pattern.compile(
"^([\\d.]+)\\s+(\\d+)\\s+([\\d.]+)\\s+(.+?)\\s+\\((\\d+)\\)(?:\\s+\\{([^{}]+))?"
);
Matcher m = p.matcher("");
Scanner sc = new Scanner(new File("C:\\Temp\\factura.txt"));
while (sc.hasNextLine())
{
String s = sc.nextLine();
if (m.reset(s).find())
{
System.out.printf("%s %8s %6s%n%s (%s) %s%n%n",
m.group(1), m.group(2), m.group(3), m.group(4), m.group(5),
m.start(6) != -1 ? m.group(6) : "");
}
}
I tried some things with regex and substring but i can't get it to work and I'm going crazy with this.我用正则表达式和子字符串尝试了一些东西,但我无法让它工作,我快要疯了。
Any help apreciated.任何帮助表示赞赏。
Try this.尝试这个。
public static void main(String[] args) {
String line="1 Juan García12-11-2016 Reparación caldera 110.50";
String amount=line.substring(line.lastIndexOf(' '),line.length());
String code=line.substring(0,line.indexOf(' '));
String remaining=line.substring(code.length(),line.lastIndexOf(' '));
//Juan García12-11-2016 Reparación caldera
remaining=remaining.trim();
Matcher matcher = Pattern.compile("\\d").matcher(remaining);
matcher.find();
int i = Integer.valueOf(matcher.group());
String name=remaining.substring(0,i);
remaining=remaining.substring(name.length(),remaining.length());
//12-11-2016 Reparación caldera
String date=remaining.split(" ")[0];
String concept=remaining.substring(date.length(),remaining.length());
concept=concept.trim();
System.out.printf("code: "+code+" client:"+name+" Date:"+date+" Concept: "+concept+" Price:"+amount);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.