Title here
Summary here
Our example demonstrates common regular expression tasks in Scala.
import scala.util.matching.Regex
object RegularExpressions {
def main(args: Array[String]): Unit = {
// This tests whether a pattern matches a string.
val patternMatch = "p([a-z]+)ch".r.matches("peach")
println(patternMatch)
// For other regex tasks, we'll use a compiled Regex object.
val r = "p([a-z]+)ch".r
// Here's a match test like we saw earlier.
println(r.matches("peach"))
// This finds the match for the regex.
println(r.findFirstIn("peach punch"))
// This finds the first match but returns the start and end indexes
// for the match instead of the matching text.
r.findFirstMatchIn("peach punch").foreach { m =>
println(s"idx: ${m.start} ${m.end}")
}
// The `Submatch` variants include information about
// both the whole-pattern matches and the submatches
// within those matches.
r.findFirstMatchIn("peach punch").foreach { m =>
println(s"${m.group(0)} ${m.group(1)}")
}
// The `findAllIn` method applies to all matches in the input,
// not just the first.
println(r.findAllIn("peach punch pinch").toList)
// Providing a limit to these functions will restrict
// the number of matches.
println(r.findAllIn("peach punch pinch").take(2).toList)
// The `replaceFirstIn` method can be used to replace
// subsets of strings with other values.
println(r.replaceFirstIn("a peach", "<fruit>"))
// The `replaceAllIn` method with a function allows you to
// transform matched text with a given function.
val result = r.replaceAllIn("a peach", m => m.group(0).toUpperCase())
println(result)
}
}
To run the program, save it as RegularExpressions.scala
and use scala
:
$ scala RegularExpressions.scala
true
true
Some(peach)
idx: 0 5
peach ea
List(peach, punch, pinch)
List(peach, punch)
a <fruit>
a PEACH
Scala’s regular expression support is provided by the scala.util.matching.Regex
class. It offers similar functionality to Go’s regexp
package, but with a more functional and Scala-idiomatic API.
For a complete reference on Scala regular expressions, check the Scala documentation for the Regex
class.