This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Regex?

1 reply
Robert Fischer
Joined: 2009-01-31,
User offline. Last seen 42 years 45 weeks ago.

Is there any documentation on using regular expressions in Scala? In particular, I'd like to
understand the String#r stunt that's going on.

scala> "(? "(? "(? "o".r.findAllIn("foo").groupCount
res6: Int = 0

scala> """o""".r.findAllIn("foo").groupCount
res7: Int = 0

~~ Robert Fischer.
Grails Trainining http://www.smokejumperit.com/grails_training.html
Smokejumper Consulting http://smokejumperit.com
Enfranchised Mind Blog http://enfranchisedmind.com/blog

Check out my book, "Grails Persistence with GORM and GSQL"!
http://www.smokejumperit.com/redirect.html

Alex Boisvert
Joined: 2008-12-16,
User offline. Last seen 42 years 45 weeks ago.
Re: Regex?
In the Predef object (which is imported by default) there is an implicit conversion to convert any String to a RichString,

 implicit def stringWrapper(x: String) = new runtime.RichString(x)

and in scala.runtime.RichString you'll find the "r" method.

  /** You can follow a string with `.r', turning
   *  it into a Regex. E.g.
   *
   *  """A\w*""".r   is the regular expression for identifiers starting with `A'.
   */
  def r: Regex = new Regex(self)

which converts the RichString to a Regex object.   The rest happens in scala.util.matching.Regex which essentially delegates to java.util.regex.{Pattern, Matcher} classes.

hope this helps,
alex

On Fri, Jan 30, 2009 at 4:03 PM, Robert Fischer <robert.fischer@smokejumperit.com> wrote:
Is there any documentation on using regular expressions in Scala?  In particular, I'd like to understand the String#r stunt that's going on.

scala> "(?<!f)o".r.findAllIn("foo")
res3: scala.util.matching.Regex.MatchIterator = non-empty iterator

scala> "(?<!f)o".r.findAllIn("foo").groupCount
res4: Int = 0

scala> "(?<!f)o".r.findAllIn("foo").groupCount
res5: Int = 0

scala> "o".r.findAllIn("foo").groupCount
res6: Int = 0

scala> """o""".r.findAllIn("foo").groupCount
res7: Int = 0


~~ Robert Fischer.
Grails Trainining      http://www.smokejumperit.com/grails_training.html
Smokejumper Consulting http://smokejumperit.com
Enfranchised Mind Blog http://enfranchisedmind.com/blog

Check out my book, "Grails Persistence with GORM and GSQL"!
http://www.smokejumperit.com/redirect.html

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland