-3

What is the idiomatic way to iterate over the matches returned by a regexp in java.

Usually the java way is the following (see How to iterate over regex expression)

Pattern p = Pattern.compile("(\\w+)=(\\w+);");
Matcher m = p.matcher(line);
while (m.find()) {
    map.put(m.group(1), m.group(2));
}

Besides the possible mistake of calling .group before .find this is imperative and as such non composable. This means that you need to create intermediate structures to store data via side effects.

How to use regex using the power of vavr iterators/collections?

raisercostin
  • 8,777
  • 5
  • 67
  • 76

1 Answers1

0

Use this simple oneliner

  //given
  Pattern pattern = Pattern.compile("(\\w+)=(\\w+);");
  String line = "name1=gil;name2=orit;";

  Iterator<Matcher> all = 
    Iterator
      .continually(pattern.matcher(line))
      .takeWhile(matcher -> matcher.find());

  //use it like
  io.vavr.collection.Map<String,String> map = 
    all.toMap(m->m.group(1),m->m.group(2));
raisercostin
  • 8,777
  • 5
  • 67
  • 76