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