Scala: How to use regex pattern matching in a match expression

Scala FAQ: How can I use regular expression (regex) pattern matching in a match expression (a Scala match/case expression)?

As I wrote in my Scala sed class post earlier today, Jon Pretty’s Kaleidoscope project lets you use string pattern-matching code in Scala match expressions. This enables regex pattern-matching code like this:

// Kaleidoscope enables this:
def updateLine(currentLine: String): String = currentLine match {
    case r"^# ${header}@(.*)"  => s"<h1>$header</h1>"  //"# foo"  -> "<h1>foo</h1>"
    case r"^## ${header}@(.*)" => s"<h2>$header</h2>"  //"## foo" -> "<h2>foo</h2>"
    case _                     => currentLine
}

That example not only shows how to use pattern-matching in a match expression, but also how to use regex capture groups.

The ability to use string pattern-matching code in a Scala match expression is a very cool and useful ability, and I didn’t realize how important it was when the Kaleidoscope project was released. This SO post shows other ways to try to use string pattern-matching in match expressions, but Kaleidoscope looks like the easiest solution.

For more information, see the Kaleidoscope project or my Scala sed class post.

All the best,
Alvin Alexander
Louisville, Colorado

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.