[英]Reading Strings from lines in Java
我有一个txt文件,格式为:
Name 'Paul' 9-years old
我如何从“阅读热线”获得:
String the_name="Paul"
和
int the_age=9
在Java中,将其余的全部丢弃?
我有:
...
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
//put the name value in the_name
//put age value in the_age
}
...
请提出建议,谢谢。
当您使用BufferedReader
且所有内容都在一行中时,您必须将其拆分以提取数据。 然后需要一些其他格式来删除引号并提取年龄的年份部分。 不需要任何花哨的正则表达式:
String[] strings = line.split(" ");
if (strings.length >= 3) {
String the_name= strings[1].replace("'", "");
String the_age = strings[2].substring(0, strings[2].indexOf("-"));
}
我注意到您在while
循环中具有此功能。 为此,请确保每一行都保留以下格式:
text 'Name' digit-any other text
^^ ^^ ^
重要的字符是
-
连字符 使用java.util.regex.Pattern:
Pattern pattern = Pattern.compile("Name '(.*)' (\d*)-years old");
for (String line : lines) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
String theName = matcher.group(1);
int theAge = Integer.parseInt(matcher.group(2));
}
}
您可以使用String.substring
, String.indexOf
, String.lastIndexOf
和Integer.parseInt
方法,如下所示:
String line = "Name 'Paul' 9-years old";
String theName = line.substring(line.indexOf("'") + 1, line.lastIndexOf("'"));
String ageStr = line.substring(line.lastIndexOf("' ") + 2, line.indexOf("-years"));
int theAge = Integer.parseInt(ageStr);
System.out.println(theName + " " + theAge);
输出:
保罗9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.