A couple new methods have just been added to Scala 2.8 Regex. You will need to download a version of Scala 2.8 more recent than Scala2.8-Beta1.
The methods are related to replacing text using a regular expression and to say they are useful is an understatement. Lets take a look:
- scala> val quote = """I don't like to commit myself about heaven and hell - you see, I have friends in both places.
- | Mark Twain"""
- quote: java.lang.String =
- I don't like to commit myself about heaven and hell - you see, I have friends in both places.
- Mark Twain
- scala> val expr = "e".r
- expr: scala.util.matching.Regex = e
- /*
- This first method is not new or is it interesting. But the new methods are both related
- so lets start with the basic form of replaceAllIn
- */
- scala> expr.replaceAllIn(quote, "**")
- res1: String =
- I don't lik** to commit mys**lf about h**av**n and h**ll - you s****, I hav** fri**nds in both plac**s.
- Mark Twain
- // this does the same thing
- scala> quote.replaceAll("e","**")
- res2: java.lang.String =
- I don't lik** to commit mys**lf about h**av**n and h**ll - you s****, I hav** fri**nds in both plac**s.
- Mark Twain
- /*
- Now things get interesting. Using this form of replaceAllIn we can determine the replacement on a case by case basis.
- It provides the Match object as the parameter so you have complete access to all
- the matched groups, the location of the match etc...
- The method takes a Match => String function. Very, very powerful.
- */
- scala> expr.replaceAllIn(quote, s => if(util.Random.nextBoolean) "?" else "*")
- res5: String =
- I don't lik? to commit mys?lf about h?av?n and h?ll - you s*?, I hav? fri*nds in both plac*s.
- Mark Twain
- /*
- Another example using some of the matcher functionality
- */
- scala> expr.replaceAllIn(quote, m => m.start.toString)
- res6: String =
- I don't lik11 to commit mys26lf about h37av40n and h48ll - you s5960, I hav68 fri73nds in both plac90s.
- Mark Twain
- /*
- Another crazy useful method is the replaceSomeIn. It is similar to the replaceAllIn that takes a function except that the function in replaceSomeIn returns an Option. If None then there is no replacement. Otherwise a replacement is performed. Very nice when dealing with complex regular expressions.
- In this example we are replacing all 'e's start are before the 50th character in the string with -
- */
- scala> expr.replaceSomeIn(quote, m => if(m.start > 50) None else Some("-"))
- res3: String =
- I don't lik- to commit mys-lf about h-av-n and h-ll - you see, I have friends in both places.
- Mark Twain
The String => String replaceAllIn has been removed. The replaceAllMatchesIn method has been renamed replaceAllIn. And there's now an replaceSomeIn, which takes a Match => Option[String]. Much happyness, but you might want to change the blog. :-)
ReplyDeleteDone. Thanks for noticing this. And I agree replaceSomeIn is a welcome addition
ReplyDelete