javajava.util.scannerreader

Read specific part of a line


I am trying to read and save in a variable only a specific part of a line when reading a line from a file.

I know how to read the whole file line per line but I can't seem to figure out how to read a specific part.

Here is the file format:

 @ARTICLE{
8249726, 
author={N. Khlif and A. Masmoudi and F. Kammoun and N. Masmoudi}, 
journal={IET Image Processing}, 
title={Secure chaotic dual encryption scheme for H.264/AVC video conferencing protection}, 
number={1}, 
year={2018}, 
volume={12}, 
pages={42-52}, 
keywords={adaptive codes;chaotic communication;cryptography;data compression;data protection;variable length codes;video coding;H.264/AVC video conferencing protection;advanced video coding protection;chaos-based crypto-compression scheme;compression ratio;context adaptive variable length coding;decision module;format compliance;inter-prediction encryption;intra-prediction encryption;piecewise linear chaotic maps;pseudorandom bit generators;secure chaotic dual encryption scheme;selective encryption approach;video compression standards}, 
doi={10.1049/iet-ipr.2017.0022}, 
ISSN={1751-9659}, 
month={Dec},
}

I only need to read and save in different variables the text between the { and }.

I have no clue how I can do this. Here is the code I tried so far:

public static void main(String[] args) {
    try {
        File myFile = new File("Latex3.bib");
        Scanner reader = new Scanner(myFile);
        while(reader.hasNextLine()) {
            System.out.println(reader.nextLine());
        }
    }catch(FileNotFoundException e) {
        e.getMessage();
    }   

Solution

  • You can solve it using regex:

    try {
            File myFile = new File("Latex3.bib");
            Scanner reader = new Scanner(myFile);
            while (reader.hasNextLine()) {
                Pattern pattern = Pattern.compile("=\\{([^}]*)");
                Matcher matcher = pattern.matcher(reader.nextLine());
                if (matcher.find()) {
                    System.out.println(matcher.group(1));
                }
            }
        } catch (FileNotFoundException e) {
            e.getMessage();
        }
    

    Use this to test your regex pattern: https://regex101.com/.

    And to learn about regex check this one: https://dev.java/learn/regex/.

    Also you can use the indexOf method from String class that will return the index of { then you substring the line from that index till the end minus 2 as the 2 last index has } and ,.