I’m pretty new to Java and I would like to know if there is an effective way of creating a substring based on conditions.
Currently I am reading from a txt file and changing that txt file to a String format using BufferedReader.
I am receiving several txt files but they all have the same format. The data that I want to extract is always on the 45th row. And the 45th row of the txt file always look something like this.
number : abcd
I want to extract the “abcd” part. It would be appreciated if anyone could tell me if there is any way to do this.
Advertisement
Answer
Read the file at specific line and Regex for the desired data:
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; class Main{ public static void main(String[] args) { try{ String line45 = Files.readAllLines(Paths.get("file.txt")).get(44); String pattern = "\: (.*)"; // Capture everything after ':' colon character Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(line45); if (m.find( )) { System.out.println("Found value: " + m.group(1) ); } }catch (IOException e) { System.out.println("entry not found."); } } }
Found value: abcd
Assign m.group(1)
to a variable and use the data as needed.