DulcetAirman

PatternStream.java

Feb 21st, 2022 (edited)
73
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin;
  2.  
  3. import java.util.Spliterator;
  4. import java.util.function.Consumer;
  5. import java.util.function.Function;
  6. import java.util.function.Supplier;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9. import java.util.stream.Stream;
  10. import java.util.stream.StreamSupport;
  11.  
  12. /** Utility class that allows you to easily process all matches using a Java Stream. */
  13. public class PatternStream {
  14.     public static void main(String[] args) {
  15.         // Simple example:
  16.         String pattern = "\\p{Alpha}+(\\d+)";
  17.         String text = "xxx foo42 %&ç bar789, zebra end.";
  18.         Stream<String> match = match(pattern, text, m -> "#" + m.group(1));
  19.         match.forEach(System.out::println);
  20.     }
  21.  
  22.     public static Stream<String> match(Pattern pattern, CharSequence input) {
  23.         return match(pattern, input, m -> m.group(0));
  24.     }
  25.  
  26.     public static Stream<String> match(String pattern, CharSequence input) {
  27.         return match(Pattern.compile(pattern), input, m -> m.group(0));
  28.     }
  29.  
  30.     public static <T> Stream<T> match(String pattern, CharSequence input, Function<? super Matcher, ? extends T> fn) {
  31.         return match(Pattern.compile(pattern), input, fn);
  32.     }
  33.  
  34.     public static <T> Stream<T> match(Pattern pattern, CharSequence input, Function<? super Matcher, ? extends T> fn) {
  35.         Supplier<Spliterator<T>> supplier = () -> {
  36.             final Matcher matcher = pattern.matcher(input);
  37.             return new Spliterator<T>() {
  38.                 @Override
  39.                 public boolean tryAdvance(Consumer<? super T> action) {
  40.                     if (!matcher.find()) return false;
  41.                     action.accept(fn.apply(matcher));
  42.                     return true;
  43.                 }
  44.  
  45.                 @Override
  46.                 public Spliterator<T> trySplit() {
  47.                     return null;
  48.                 }
  49.  
  50.                 @Override
  51.                 public long estimateSize() {
  52.                     return Long.MAX_VALUE;
  53.                 }
  54.  
  55.                 @Override
  56.                 public int characteristics() {
  57.                     return ORDERED | IMMUTABLE;
  58.                 }
  59.             };
  60.         };
  61.         return StreamSupport.stream(supplier, Spliterator.ORDERED | Spliterator.IMMUTABLE, false);
  62.     }
  63. }
  64.  
RAW Paste Data Copied