Search code examples
javastringspecial-charactersreadline

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.


Solution

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