diff options
-rw-r--r-- | src/library/scala/util/matching/Regex.scala | 5 | ||||
-rw-r--r-- | test/files/run/ReplacementMatching.scala | 21 |
2 files changed, 25 insertions, 1 deletions
diff --git a/src/library/scala/util/matching/Regex.scala b/src/library/scala/util/matching/Regex.scala index 951dea11c4..c9c7257241 100644 --- a/src/library/scala/util/matching/Regex.scala +++ b/src/library/scala/util/matching/Regex.scala @@ -289,6 +289,11 @@ object Regex { def unapply(m: Match): Some[String] = Some(m.matched) } + /** An extractor object that yields groups in the match. */ + object Groups { + def unapplySeq(m: Match): Option[Seq[String]] = if (m.groupCount > 0) Some(1 to m.groupCount map m.group) else None + } + /** A class to step through a sequence of regex matches */ class MatchIterator(val source: java.lang.CharSequence, val regex: Regex, val groupNames: Seq[String]) diff --git a/test/files/run/ReplacementMatching.scala b/test/files/run/ReplacementMatching.scala index ab14202871..64a912392b 100644 --- a/test/files/run/ReplacementMatching.scala +++ b/test/files/run/ReplacementMatching.scala @@ -1,7 +1,7 @@ - +import util.matching._ @@ -9,6 +9,11 @@ object Test { def main(args: Array[String]) { + replacementMatching + groupsMatching + } + + def replacementMatching { val regex = """\$\{(.+?)\}""".r val replaced = regex.replaceAllMatchDataIn("Replacing: ${main}. And another method: ${foo}.", (m: util.matching.Regex.Match) => { @@ -24,4 +29,18 @@ object Test { assert(replaced2 == "Replacing: main. And then one more: bar.") } + def groupsMatching { + val Date = """(\d+)/(\d+)/(\d+)""".r + for (Regex.Groups(a, b, c) <- Date findFirstMatchIn "1/1/2001 marks the start of the millenium. 31/12/2000 doesn't.") { + assert(a == "1") + assert(b == "1") + assert(c == "2001") + } + for (Regex.Groups(a, b, c) <- (Date findAllIn "1/1/2001 marks the start of the millenium. 31/12/2000 doesn't.").matchData) { + assert(a == "1" || a == "31") + assert(b == "1" || b == "12") + assert(c == "2001" || c == "2000") + } + } + } |