简体   繁体   English

用Java解析文本文件

[英]Parsing text file in Java

I have a text file that contains one line. 我有一个包含一行的文本文件。 Something like this: A10102012MikeM. 像这样的东西:A10102012MikeM。 The first letter can be either A or P, following numbers correspond to date, next comes name, and then gender(M or F). 第一个字母可以是A或P,下面的数字对应于日期,下一个是姓名,然后是性别(M或F)。 What is the best method to parse this info into Map ? 将此信息解析为Map的最佳方法是什么? Of course i can take string.substring(x,y) of each element. 当然我可以采用每个元素的string.substring(x,y)。 But it seems too hard-coded. 但它似乎太难编码了。 Can this be accomplished with regex somehow?? 这可以用正则表达式以某种方式实现吗?

Try this regex ^(A|P)(\\d+)(\\w+?)(M|F)$ .This will work but some conditions: 试试这个正则表达式^(A|P)(\\d+)(\\w+?)(M|F)$ 。这会有效但有些条件:

1) It will not check date validity. 1)它不会检查日期有效性。

2) Output should be exactly as you described otherwise it may fail. 2)输出应完全按照您的描述输出,否则可能会失败。

String str = "A10102012MikeM";

String p = "^([A|P])(\\d+)(\\w+?)(M|F)$";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(str);
if (matcher.find()){
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
}

output = 输出=

A 10102012 Mike M A 10102012 Mike M

Yes, Java has very good support for regexes. 是的,Java对正则表达式有很好的支持。 You will want to check out java.util.regex.Pattern . 您需要查看java.util.regex.Pattern Pay special attention to the Matcher groups which will let you extract data from the regex matches. 特别注意Matcher组,它们可以让您从正则表达式匹配中提取数据。

^(A|P)([0-9]){10}(.+)(M|F)$

  • Group 1 ... A or P 第1组...... A或P.
  • Group 2 ... 10 digit date 第2组...... 10位数日期
  • Group 3 ... The name 第3组......名称
  • Group 4 ... M or F (gender) 第4组...... M或F(性别)
^([AP])(\d+)([A-Za-z]+?)([MF])$

这个正则表达式(转义未完成)将不同部分的数据捕获到组中,以便您可以更轻松地获取它们。

A possible alternative to regex, depending on your exact situation, may be the flatworm project on sourceforge. 根据您的具体情况,正则表达式的可能替代方案可能是sourceforge上的扁虫项目。 For example, it can read the text file and populate java objects for you. 例如,它可以读取文本文件并为您填充java对象。

They've got a good field guide that walks through a number of use cases. 他们有一个很好的现场指南 ,介绍了一些用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM