Search code examples
parsingreturn-valueprintln

How to print specific value from line in a file


I have created a search that will find data in a file. The data that gets printed contains a value that I would like to be shown instead of the whole line.

With the below code, I search for OMXS303F; and get this as result: BDt;i4244190;Si26944;s6;Ex4206868;Mk4206874;INiFXS30;SYmOMXS303F;ISnSE0016998389;CUtSEK;PRt1;VOd1;Cf1;TTd20230616;CFcFFICSX;ITSz4206882;NDp6;MPmN;MPaN;NDTp6;ITStN;STy2;AUmY;LSz1;
This is what I would like to have as a result instead: i4244190

All help or suggestions would be much appreciated.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

public class FileReadContent {

    public static void main(String[] args) throws IOException {
        System.out.println("Enter date YYYY-MM-DD: ");
        Scanner dateInput = new Scanner(System.in);
        String date = dateInput.next();
        Path pathFileToRead = Paths.get("c:\\tmp\\data-full-"+date+".tip");
        
        System.out.println("Enter symbol: ");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String symbol = reader.readLine();
        
        Files.lines(pathFileToRead)
            .filter(str -> str.contains(symbol))
            .forEach(System.out::println);

        dateInput.close();
        reader.close();
    }

}

Solution

  • This did solve the issue:

        StringBuilder contentBuilder = new StringBuilder();
        Files.lines(pathFileToRead)
            .filter(str -> str.contains(symbol))
            .forEach(s -> contentBuilder.append(s).append("\n"));
        String fileContent = contentBuilder.toString(); 
    
        String r = ";i.*?(?=;)+;";
        Pattern p = Pattern.compile(r);
        Matcher m = p.matcher(fileContent);
        while (m.find()) {
            System.out.println(m.group());