Regular expressions: Difference between revisions

m (→‎{{header|Python}}: fix 1 line)
Line 1,664:
 
=={{header|Scala}}==
[[Category:Scala Implementations]]
{{libheader|Scala}}
Define
<lang scalaScala>val Bottles1 = "(\\d+) bottles of beer".r // syntactic sugar
val Bottles2 = """(\d+) bottles of beer""".r // using triple-quotes to preserve backslashes
val Bottles3 = new scala.util.matching.Regex("(\\d+) bottles of beer") // standard
Line 1,681 ⟶ 1,683:
Bottles4 findFirstMatchIn "99 bottles of beer" // returns a "Match" object, or None
Bottles4 findPrefixMatchOf "99 bottles of beer" // same thing, for prefixes
val bottles = (Bottles4 findFirstMatchIn "99 bottles of beer").get.group("bottles") // Getting a group by name</lang>
val Bottles4(bottles) = "99 bottles of beer" // syntactic sugar (not using group name)</lang>
 
Using pattern matching with regex:
<lang scalaScala>val Some(bottles) = Bottles4 findPrefixOf "99 bottles of beer" // throws an exception if the matching fails; full string must match
for {
line <- """|99 bottles of beer on the wall
Line 1,700 ⟶ 1,701:
 
Replacing with regex:
<lang scalaScala>Bottles2 replaceFirstIn ("99 bottles of beer", "98 bottles of beer")
Bottles3 replaceAllIn ("99 bottles of beer", "98 bottles of beer")</lang>
 
Anonymous user