RNO
RNO

Reputation: 223

Reading Strings from lines in Java

I have a txt file formatted like:

Name 'Paul' 9-years old

How can I get from a "readline":

String the_name="Paul"

and

int the_age=9

in Java, discarding all the rest?

I have:

  ...       
    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

    }
...

Please suggest, thanks.

Upvotes: 0

Views: 410

Answers (3)

Reimeus
Reimeus

Reputation: 159784

As you're using BufferedReader and everything is on the one line, you would have to split it to extract the data. Some additional formatting is then required to remove the quotes & extract the year part of age. No need for any fancy regex:

String[] strings = line.split(" ");
if (strings.length >= 3) {
   String the_name= strings[1].replace("'", "");
   String the_age = strings[2].substring(0, strings[2].indexOf("-"));
}

I notice you have this functionality in a while loop. For this to work, make sure that every line keeps the format:

text 'Name' digit-any other text
    ^^    ^^     ^

Important chars are

  • Spaces: min of 3 tokens needed for split array
  • Single quotes
  • - Hyphen character

Upvotes: 2

ugh
ugh

Reputation: 26

use 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));
    }
}

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can use the String.substring, String.indexOf, String.lastIndexOf, and Integer.parseInt methods as follows:

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);

Output:

Paul 9

Upvotes: 0

Related Questions