It seems to be a common anti-pattern to go for Files.lines
, whenever a Stream
over a file is needed, regardless of whether processing individual lines is actually needed.
The first tool of your choice, when pattern matching over a file is needed, should be Scanner
:
Pattern p = Pattern.compile(
"REPORT ID: ABCD\\s*\\R"
+"TAG1\\s*:\\s*(.*?)\\R"
+"DATA1\\s*:\\s*(.*?)\\R"
+"DATA2\\s*:\\s*(.*?)\\R"
+"DATA3\\s*:\\s*(.*?)\\R"); // you can keep this in a static final field
try(Scanner sc = new Scanner(filePath, StandardCharsets.UTF_8);
Stream<MatchResult> st = sc.findAll(p)) {
st.forEach(mr -> System.out.println("found tag1: " + mr.group(1)
+ ", data: "+String.join(", ", mr.group(2), mr.group(3), mr.group(4))));
}
It's easy to adapt the pattern, i.e. use
Pattern p = Pattern.compile(
"REPORT ID: ABCD\\s*\\R"
+"TAG1: (1000375351 PR)\\R"
+"DATA1\\s*:\\s*(.*?)\\R"
+"DATA2\\s*:\\s*(.*?)\\R"
+"DATA3\\s*:\\s*(.*?)\\R"); // you can keep this in a static final field
as pattern to fulfill your more complex criteria.
But you could also provide arbitrary filter conditions in the Stream:
Pattern p = Pattern.compile(
"REPORT ID: (.*?)\\s*\\R"
+"TAG1: (.*?)\\R"
+"DATA1\\s*:\\s*(.*?)\\R"
+"DATA2\\s*:\\s*(.*?)\\R"
+"DATA3\\s*:\\s*(.*?)\\R"); // you can keep this in a static final field
try(Scanner sc = new Scanner(filePath, StandardCharsets.UTF_8);
Stream<MatchResult> st = sc.findAll(p)) {
st.filter(mr -> mr.group(1).equals("ABCD") && mr.group(2).equals("1000375351 PR"))
.forEach(mr -> System.out.println(
"found data: " + String.join(", ", mr.group(3), mr.group(4), mr.group(5))));
}
allowing more complex constructs than the equals
calls of the example. (Note that the group numbers changed for this example.)
E.g., to support a variable order of the data items after the “REPORT ID”, you can use
Pattern p = Pattern.compile("REPORT ID: (.*?)\\s*\\R(((TAG1|DATA[1-3])\\s*:.*?\\R){4})");
Pattern nl = Pattern.compile("\\R"), sep = Pattern.compile("\\s*:\\s*");
try(Scanner sc = new Scanner(filePath, StandardCharsets.UTF_8);
Stream<MatchResult> st = sc.findAll(p)) {
st.filter(mr -> mr.group(1).equals("ABCD"))
.map(mr -> nl.splitAsStream(mr.group(2))
.map(s -> sep.split(s, 2))
.collect(Collectors.toMap(a -> a[0], a -> a[1])))
.filter(map -> "1000375351 PR".equals(map.get("TAG1")))
.forEach(map -> System.out.println("found data: " + map));
}
findAll
is available in Java 9, but if you have to support Java 8, you can use the findAll
implementation of this answer.