SCALA : Finding Patterns in Strings

Table of contents
Reading Time: < 1 minute

To determine whether a String contains a regular expression pattern , create a “regex object” by using “.r” method on a string .

And then use the pattern with findFirstIn when you’re looking for one match, and findAllIn when looking for all matches.

First create a Regex for the pattern you want to search for, in this case, a sequence of one or more numeric characters:

Next, create a sample String you can search:

The findFirstIn method finds the first match:

When looking for multiple matches, use the findAllIn method:

As you can see, findAllIn returns an iterator, which lets you loop over the results:

If findAllIn doesn’t find any results, an empty iterator is returned, so you can still write your code just like that—you don’t need to check to see if the result is null. If you’drather have the results as an Array, add the toArraymethod after the findAllIn call:

If there are no matches, this approach yields an empty Array. Other methods like toList, toSeq, and toVector are also available. You can also create regex object by importing the Regex class