Home > Enterprise >  Java Substring based on condtion
Java Substring based on condtion

Time:10-19

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.

CodePudding user response:

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.

CodePudding user response:

This should work:

String s = stringFromTextFile;
s = s.split(":")[1];
s = s.substring(1, s.length());
System.out.println("Abcd: "   s);

The line s = s.split(":")[1] essentially makes an array of the 2 elements. For example, entry 0 would be 'number ', and entry 1 would be ' abcd'. Then, s = s.substring(1, s.length()) removes the space at the beginning of ' abcd', turning it into 'abcd'.

Disclaimer: This code is not fully tested, so some errors may occur.

CodePudding user response:

Read the file contents as list of Strings

    Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset());

and get the 45th element, then split by : and get the second array element.

  • Related