0

I would like to extract The Name and Age from The Text file from it. Can someone please provide me some help?

The text content :

fhsdgjfsdk;snfd fsd ;lknf;ksld sldkfj lk 
Name: Max Pain
Age: 99 Years
and they df;ml dk fdj,nbfdlkn ......

Code:

package myclass;

import java.io.*;

public class ReadFromFile2 {
    public static void main(String[] args)throws Exception {
        File file = new File("C:\\Users\\Ss\\Desktop\\s.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String st;
        while ((st = br.readLine()) != null)
            System.out.println(st.substring(st.lastIndexOf("Name:")));
            // System.out.println(st);
    }
}
0009laH
  • 1,960
  • 13
  • 27
Sam
  • 49
  • 6
  • 1
    This question needs some kind of limitations. Is it guaranteed, that name and age will be on separate lines? Is it guaranteed, that lines containing age and name will not contain any other random characters? – Steyrix Jan 09 '20 at 11:21
  • 1
    `lastIndexOf("Name:")` returns `-1` if not found, so you need an `if` statement to check that. Also, if found, it returns the index of the `N` letter, so you need to add 5 (or 6) to the value to get `Max Pain`, not `Name: Max Pain`. Now try writing the code. – Andreas Jan 09 '20 at 11:25
  • `public static void main(String[] args) { String s = ""; String str = "fhsdgjfsdk;snfd fsd ;lknf;ksld sldkfj lk Name: Max Pain Age: 99 Years and they df;ml dk fdj,nbfdlkn"; Pattern pattern = Pattern.compile("Name:(.*?)Years", Pattern.DOTALL); String[] result = pattern.split(str); Matcher matcher = pattern.matcher(str); while (matcher.find()) { s = matcher.group(); } String[] split = s.split("(Name:|Age:|Years)"); Arrays.stream(split).forEach(System.out::println); }` **Must work for you** – Vishwa Ratna Jan 09 '20 at 12:14
  • If you don't reply, how would we know if the problem is solved or you need more explanation? – Vishwa Ratna Jan 10 '20 at 12:58
  • i just want also to Print The Word "Name:" and "Age:"! thats mean: Name: Max Pain Age: 99 Years – Sam Jan 10 '20 at 14:36

4 Answers4

0

You can use replace method from string class, since String is immutable and is going to create a new string for each modification.

while ((st = br.readLine()) != null) 
      if(st.startsWith("Name:")) {
          String name = st.replace("Name:", "").trim();
          st = br.readLine();
          String age="";
          if(st!= null && st.startsWith("Age:")) {
             age = st.replace("Age:", "").trim();
          }
          // now you should have the name and the age in those variables
      }

  } 
Vladucu Voican
  • 283
  • 1
  • 10
  • What if there is no space after the `:` colon? Would be much better to use the same string in the `startsWith` and `replace` methods. Would be even better to simply use a `substring` instead of asking `replace` to scan the string again. – Andreas Jan 09 '20 at 11:30
  • You can still use `replace` but without the space, and afterwards just do a `string.trim()` . I changed it to that one since it's safer. Either way, in the case that the file doesn't have a correct structure, it's easier to use pattern matching with `regex`. – Vladucu Voican Jan 09 '20 at 11:32
  • 1) Too many close-parentheses on both `replace` calls. --- 2) *"easier to use pattern matching with regex"* You're not using regex anywhere in that code, so why did you say that? – Andreas Jan 09 '20 at 11:38
  • @Andreas 1) good catch, I will correct it . 2) yes I know, I said that as an alternative in case the format of the file doesn't respect a certain standard – Vladucu Voican Jan 09 '20 at 11:49
0

please try below code.

public static void main(String[] args)throws Exception 
      { 
      File file = new File("/root/test.txt"); 

      BufferedReader br = new BufferedReader(new FileReader(file)); 

      String st; 
      while ((st = br.readLine()) != null) {

          if(st.lastIndexOf("Name:") >= 0 || st.lastIndexOf("Age:") >= 0) {
              System.out.println(st.substring(st.lastIndexOf(":")+1));
          }
      }
      }
Ranjith Bokkala
  • 379
  • 1
  • 10
0

This will do your Job:

public static void main(String[] args) {
    String str = "fhsdgjfsdk;snfd fsd ;lknf;ksld sldkfj lk Name: Max Pain Age: 99 Years and they df;ml dk fdj,nbfdlkn";
    String[] split = str.split("(\\b: \\b)"); 
    //\b represents an anchor like caret 
    // (it is similar to $ and ^) 
    // matching positions where one side is a word character (like \w) and 
    // the other side is not a word character 
    // (for instance it may be the beginning of the string or a space character).
    System.out.println(split[1].replace("Age",""));
    System.out.println(split[2].replaceAll("\\D+",""));  
    //remove everything except Integer ,i.e. Age
}

Output:

Max Pain 
99
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0

If they can occur on the same line and you want to use a pattern don't over matching them, you could use a capturing group and a tempered greedy token.

\b(?:Name|Age):\h*((?:.(?!(?:Name|Age):))+)

Regex demo | Java demo

For example

final String regex = "\\b(?:Name|Age):\\h*((?:.(?!(?:Name|Age):))+)";
final String string = "fhsdgjfsdk;snfd fsd ;lknf;ksld sldkfj lk \n"
     + "Name: Max Pain\n"
     + "Age: 99 Years\n"
     + "and they df;ml dk fdj,nbfdlkn ......\n\n"
     + "fhsdgjfsdk;snfd fsd ;lknf;ksld sldkfj lk \n"
     + "Name: Max Pain Age: 99 Years\n"
     + "and they df;ml dk fdj,nbfdlkn ......";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println(matcher.group(i));
    }
}

Output

Max Pain
99 Years
Max Pain
99 Years
The fourth bird
  • 154,723
  • 16
  • 55
  • 70