TryThis
TryThis

Reputation: 374

Include delimiter in token when using Scanner in Java

I want to use Java Scanner object to read file line "blocks" into objects. The delimiter needs to be included in token. I tried using regex lookbehind, but delimitter is variable length. Does anyone have suggestions or alternatives for getting the delimiter?

Java code I currently have (which erroneously removes the "Processed Value" line):

ArrayList<ProcessedData> stack = new ArrayList<ProcessedData>();    

Scanner scanner = new Scanner(new File("/home/user/data.txt"));
Pattern pattern = Pattern.compile("Processed Value.+?\\n+", Pattern.UNIX_LINES);
scanner.useDelimiter(pattern);

while(scanner.hasNext()) {
    stack.add(new ProcessedData(scanner.next()));
}

Example file:

Id: 1
Raw Value: 1234
Processed Value{423}: A3s2344

Id: 36
Raw Value: 389001
Processed Value{2}: "Access Success"

Id: 28934
Raw Value: 2402
Processed Value: 1345.2 seconds

Upvotes: 2

Views: 1419

Answers (2)

Pshemo
Pshemo

Reputation: 124225

It seems that you have one empty line between informations you need so maybe try to split your data on that empty line. You can try with this delimiter

Pattern pattern = Pattern.compile("(\r?\n){2,}");
scanner.useDelimiter(pattern);

DEMO

Upvotes: 1

anubhava
anubhava

Reputation: 785108

You can use lookahead in your regex:

Pattern pattern = Pattern.compile("(?=Processed Value.+?\\n+)", Pattern.UNIX_LINES);

Upvotes: 0

Related Questions