Regular Expression

These examples use Scala on the JVM, whose regular-expression syntax is based on Java Pattern. Other engines and Unicode flags can behave differently.

Characters and character classes

Pattern Default JVM meaning
\d / \D ASCII digit / its complement; Unicode character-class mode changes predefined classes.
\w / \W ASCII letter, digit or underscore / its complement by default.
\s / \S Whitespace / its complement; the accepted set depends on flags.
. One character except line terminators by default; DOTALL (?s) includes them.
[abc] / [^abc] One listed character / one character outside the set.
[a-z0-9] One lowercase ASCII letter or digit.

The backslash belongs to both regex syntax and ordinary Scala string escaping. Triple-quoted strings make the regex easier to read:

val digit = "\\d".r          // ordinary Scala string
val sameDigit = """\d""".r    // triple-quoted Scala string
val digits = """\d+""".r
digits.findFirstIn("room 204") // Some("204")

Repetition and alternatives

  • ?, * and + mean zero-or-one, zero-or-more and one-or-more repetitions of the preceding token/group.
  • {m}, {m,n} and {m,} specify exact, bounded and lower-bounded repetition.
  • (foo|bar) selects an alternative; parentheses also capture, while (?:foo|bar) does not capture.
  • .* permits zero characters and normally stops at a line terminator. It does not capture unless placed inside a capturing group.

Find a substring versus validate the whole input

findFirstIn searches within an input. A Scala regex extractor normally matches the whole input; .unanchored changes that. ^ and $ are input-boundary anchors by default, with multiline mode changing line-boundary behavior; $ also has a final-terminator exception. Use \A and \z for strict input boundaries.

val filename = """\A(IMG\d+)\.png\z""".r
"IMG204.png" match {
  case filename(stem) => println(stem) // IMG204
  case _              => println("Not a matching filename")
}

Literal punctuation

A dot, question mark and other metacharacters need escaping when meant literally. For an arbitrary user-supplied literal, prefer Pattern.quote rather than assembling escapes manually.

val sentence = """\A\d+ files? found\?\z""".r
val examples = List("1 file found?", "2 files found?", "No files found.")
examples.map(s => sentence.pattern.matcher(s).matches())
// List(true, true, false)

Takeaway

Choose search or whole-input matching deliberately, distinguish Scala string escaping from regex escaping, and test newlines, empty input and Unicode. Avoid deeply nested ambiguous quantifiers for untrusted long inputs because backtracking can become expensive.

References: JVM Pattern syntax; Scala Regex API.