mkaz solutions log » home

Using Regular Expressions in Scala

Date: May 24, 2011

The easiest way of creating a regular expression in scala is by simply applying the .r method to a string. This creates a regular expression object, which then can be used to match and/or replace. See Regex API for available methods.

Regular Expression - Linkify a string

This regular expression will find a URL in a string and autolink it, replacing it with an HTML version of the link.
  var linked = "Some text. http://mkaz.com/ and a link"
  val regexUrl = """http:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+""".r
  linked = regexUrl.replaceAllIn(linked, "<a href=\"$0\">$0</a>")

Regular Expression - check if there is a match

Here is a function I wrote to return a flag if the string matched a word list, I needed a case insensitive match otherwise I could have simply used contains. I’m not sure if my solution is the most efficient way of doing this one, feels a bit ugly to me, but it works. I’m open for improvements.

  def existsFlag(str: String) = {
     var rtn = 0
     val words = List("dress", "choir", "youtube")
     words foreach { word =>
        val rx = ("(?i)"+word).r   // (?i) is used for case insensitive
        rx.findFirstMatchIn(str) match { 
          case Some(thing) => rtn = 1; 
          case _ => 0  // I dont want to do anything with this case
    }
    rtn
  }