O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 20

Irregular Expressions

You may have heard the old joke: "A developer has a problem and decides to solve it with a regular expression. Now they have two problems." Regular expressions can indeed get complicated quickly. But they are also very powerful, and can be extremely useful if used judiciously.

Scala's scala.util.matching.Regex class provides utility functions for regular expressions. Its findAllIn method returns a MatchIterator that iterates over all the occurrences of the regular expression in a string:

  scala> for (reMatch <- "l".r.findAllIn("I love Scala")) 
           println(reMatch)
  l
  l

In the next example, a MatchIterator is twice queried for the index of the first regular expression match in a string using the start method. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required