0

我有一个 txt 文件,格式如下:

Name 'Paul' 9-years old

我如何从“readline”中获取:

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

    }
...

请建议,谢谢。

4

3 回答 3

2

当您使用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
    ^^    ^^     ^

重要的字符是

  • 空格:拆分数组所需的最少 3 个标记
  • 单引号
  • -连字符
于 2012-11-09T23:27:11.663 回答
1

使用 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));
    }
}
于 2012-11-10T00:41:47.173 回答
0

您可以使用String.substringString.indexOfString.lastIndexOfInteger.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

于 2012-11-09T23:33:16.093 回答