"); try (Stream

Apply template in file stream

public final Pattern PATTERN = Pattern.compile("<abc:c\\sabc:name=\"(\\S+)\"\\sabc:type=\"(\\S+)\">"); try (Stream<String> stream = Files.lines(template.getPath())) { stream.filter(s -> PATTERN.matcher(s).find()).forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } 

The drawing works fine, but how can I catch / get my groups? At the moment, I only get strings.

+5
source share
1 answer

If the template that you apply appears only once per line, you can map your Stream<String> to Stream<Matcher> , filter the lines matching the template, and finally extract groups 1 and 2, saving them to an array.

 try (Stream<String> stream = Files.lines(Paths.get(""))) { stream.map(PATTERN::matcher) .filter(Matcher::find) .map(m -> new String[] { m.group(1), m.group(2) }) .forEach(a -> System.out.println(Arrays.toString(a))); } catch (IOException e) { e.printStackTrace(); } 

If the pattern appears more than once, we will need to iterate over Matcher until find() returns false . In this case, we could have

 try (Stream<String> stream = Files.lines(Paths.get(""))) { stream.map(PATTERN::matcher) .flatMap(m -> { List<String[]> list = new ArrayList<>(); while (m.find()) { list.add(new String[] { m.group(1), m.group(2) }); } return list.stream(); }) .forEach(a -> System.out.println(Arrays.toString(a))); 

In Java 9, there may be a new Matcher.results() method to get Stream<MatchResult> results. We could use it here instead of two separate find and group operations.

+7
source

Source: https://habr.com/ru/post/1241733/


All Articles