Skip to content
Advertisement

How to split a readLine but dont split values inside apostrophes?

Example txt file

ADD 'Cordless Screwdriver' 30 1 2
COST 'Multi Bit Ratcheting'
FIND 'Thermostat'
FIND 'Hand Truck'
SELL 'Hammer' 1
QUANTITY 'Paint Can'
FIRE 'Joshua Filler'
HIRE 'Lewis hamilton' 35 G
PROMOTE 'Lewis hamilton' M
SCHEDULE

Code

File inputFile = new File("src/edu/iu/c212/resources/input.txt");
        String[] inputWords = null;
        FileReader inputReader = new FileReader(inputFile);
        BufferedReader bri = new BufferedReader(inputReader);
        String y;
        while ((y = bri.readLine()) != null) {
            inputWords = y.split(" ");

--- Project Code That Handles Split Up Lines ---

}

Is there a way I can have the split not split items within the apostrophes when going across the line? That way regardless if the first Item is one word or two words, if I call inputWords[1] It will always return the full string.

What happens: “Multi Bit Ratcheting” -> inputWords[1] -> ‘Multi

What I want: “Multi Bit Ratcheting” -> inputWords[1] -> ‘Multi Bit Ratcheting’

Advertisement

Answer

You could apply a regex find all to each line using the pattern '.*?'|S+:

String line = "ADD 'Cordless Screwdriver' 30 1 2";
String[] matches = Pattern.compile("'.*?'|\S+")
                      .matcher(line)
                      .results()
                      .map(MatchResult::group)
                      .toArray(String[]::new);
System.out.println(Arrays.toString(matches));
// [ADD, 'Cordless Screwdriver', 30, 1, 2]

You may apply the above logic to each line from the file. You should, however, define the pattern outside the loop so that it doesn’t have to be recompiled for every line.

Your updated code:

File inputFile = new File("src/edu/iu/c212/resources/input.txt");
FileReader inputReader = new FileReader(inputFile);
BufferedReader bri = new BufferedReader(inputReader);
Pattern r = Pattern.compile("'.*?'|\S+");
String y;
while ((y = bri.readLine()) != null) {
    List<String> items = new ArrayList<>();
    Matcher m = r.matcher(y);
    while (m.find()) {
        items.add(m.group());
    }

    // use the list here...
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement