SCALA : Finding Patterns in Strings


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:

scala> val numPattern = "[0-9]+".r

numPattern: scala.util.matching.Regex = [0-9]+

Next, create a sample String you can search:

scala> val address = "123 Main XYZ"

address: java.lang.String = 123 Main XYZ

The findFirstIn method finds the first match:

scala> val match1 = numPattern.findFirstIn(address)

match1: Option[String] = Some(123)

When looking for multiple matches, use the findAllIn method:

scala> val matches = numPattern.findAllIn(address)

matches: scala.util.matching.Regex.MatchIterator = non-empty iterator

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

scala> matches.foreach(println)

123

101

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:

scala> val matches = numPattern.findAllIn(address).toArray

matches: Array[String] = Array(123, 101)

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

scala> import scala.util.matching.Regex

import scala.util.matching.Regex

scala> val numPattern = new Regex("[0-9]+")

numPattern: scala.util.matching.Regex = [0-9]+

About Malti Yadav

An enthusiastic technologist , Scala developer, positive attitude and the desire to go extra mile .
This entry was posted in Scala and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s