scala.util.matching.Regex.MatchIterator

class MatchIterator extends AbstractIterator[String] with Iterator[String] with MatchData

A class to step through a sequence of regex matches.

All methods inherited from scala.util.matching.Regex.MatchData will throw a java.lang.IllegalStateException until the matcher is initialized. The matcher can be initialized by calling hasNext or next() or causing these methods to be called, such as by invoking toString or iterating through the iterator’s elements.

Type Members

class GroupedIterator[B >: A] extends AbstractIterator[Seq[B]] with Iterator[Seq[B]]

A flexible iterator for transforming an Iterator[A] into an Iterator[Seq[A]], with configurable sequence size, step, and strategy for dealing with elements which don’t fit evenly.

Typical uses can be achieved via methods grouped and sliding .

  • Definition Classes
    • Iterator

Value Members From scala.collection.Iterator

def ++[B >: String](that: ⇒ GenTraversableOnce[B]): collection.Iterator[B]

[use case]

Concatenates this iterator with another.

  • that
    • the other iterator
  • returns
    • a new iterator that first yields the values produced by this iterator followed by the values produced by iterator that .
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def buffered: collection.BufferedIterator[String]

Creates a buffered iterator from this iterator.

  • returns
    • a buffered iterator producing the same values as this iterator.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.
  • See also
    • scala.collection.BufferedIterator

(defined at scala.collection.Iterator)

def collect[B](pf: PartialFunction[String, B]): collection.Iterator[B]

Creates an iterator by transforming values produced by this iterator with a partial function, dropping those values for which the partial function is not defined.

  • pf
    • the partial function which filters and maps the iterator.
  • returns
    • a new iterator which yields each value x produced by this iterator for which pf is defined the image pf(x) .
  • Definition Classes
    • Iterator
  • Annotations
    • @migration
  • Migration
    • (Changed in version 2.8.0) collect has changed. The previous behavior can be reproduced with toSeq .
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def contains(elem: Any): Boolean

Tests whether this iterator contains a given value as an element.

Note: may not terminate for infinite iterators.

  • elem
    • the element to test.
  • returns
    • true if this iterator produces some value that is is equal (as determined by == ) to elem , false otherwise.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def copyToArray[B >: String](xs: Array[B], start: Int, len: Int): Unit

[use case]

Copies selected values produced by this iterator to an array. Fills the given array xs starting at index start with at most len values produced by this iterator. Copying will stop once either the end of the current iterator is reached, or the end of the array is reached, or len elements have been copied.

Note: will not terminate for infinite iterators.

  • xs
    • the array to fill.
  • start
    • the starting index.
  • len
    • the maximal number of elements to copy.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def corresponds[B](that: GenTraversableOnce[B])(p: (String, B) ⇒ Boolean): Boolean

Tests whether every element of this iterator relates to the corresponding element of another collection by satisfying a test predicate.

  • B
    • the type of the elements of that
  • that
    • the other collection
  • p
    • the test predicate, which relates elements from both collections
  • returns
    • true if both collections have the same length and p(x, y) is true for all corresponding elements x of this iterator and y of that , otherwise false
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def drop(n: Int): collection.Iterator[String]

Advances this iterator past the first n elements, or the length of the iterator, whichever is smaller.

  • n
    • the number of elements to drop
  • returns
    • an iterator which produces all values of the current iterator, except it omits the first n values.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def dropWhile(p: (String) ⇒ Boolean): collection.Iterator[String]

Skips longest sequence of elements of this iterator which satisfy given predicate p , and returns an iterator of the remaining elements.

  • p
    • the predicate used to skip elements.
  • returns
    • an iterator consisting of the remaining elements
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def duplicate: (collection.Iterator[String], collection.Iterator[String])

Creates two new iterators that both iterate over the same elements as this iterator (in the same order). The duplicate iterators are considered equal if they are positioned at the same element.

Given that most methods on iterators will make the original iterator unfit for further use, this methods provides a reliable way of calling multiple such methods on an iterator.

  • returns
    • a pair of iterators
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterators that were returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterators as well., The implementation may allocate temporary storage for elements iterated by one iterator but not yet by the other.

(defined at scala.collection.Iterator)

def exists(p: (String) ⇒ Boolean): Boolean

Tests whether a predicate holds for some of the values produced by this iterator.

Note: may not terminate for infinite iterators.

  • p
    • the predicate used to test elements.
  • returns
    • true if the given predicate p holds for some of the values produced by this iterator, otherwise false .
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def filter(p: (String) ⇒ Boolean): collection.Iterator[String]

Returns an iterator over all the elements of this iterator that satisfy the predicate p . The order of the elements is preserved.

  • p
    • the predicate used to test values.
  • returns
    • an iterator which produces those values of this iterator which satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def filterNot(p: (String) ⇒ Boolean): collection.Iterator[String]

Creates an iterator over all the elements of this iterator which do not satisfy a predicate p.

  • p
    • the predicate used to test values.
  • returns
    • an iterator which produces those values of this iterator which do not satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def find(p: (String) ⇒ Boolean): Option[String]

Finds the first value produced by the iterator satisfying a predicate, if any.

Note: may not terminate for infinite iterators.

  • p
    • the predicate used to test values.
  • returns
    • an option value containing the first value produced by the iterator that satisfies predicate p , or None if none exists.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def flatMap[B](f: (String) ⇒ GenTraversableOnce[B]): collection.Iterator[B]

Creates a new iterator by applying a function to all values produced by this iterator and concatenating the results.

  • f
    • the function to apply on each element.
  • returns
    • the iterator resulting from applying the given iterator-valued function f to each value produced by this iterator and concatenating the results.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def forall(p: (String) ⇒ Boolean): Boolean

Tests whether a predicate holds for all values produced by this iterator.

Note: may not terminate for infinite iterators.

  • p
    • the predicate used to test elements.
  • returns
    • true if the given predicate p holds for all values produced by this iterator, otherwise false .
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def foreach[U](f: (String) ⇒ U): Unit

[use case]

Applies a function f to all values produced by this iterator.

  • f
    • the function that is applied for its side-effect to every element. The result of function f is discarded.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def grouped[B >: String](size: Int): GroupedIterator[B]

Returns an iterator which groups this iterator into fixed size blocks. Example usages:

// Returns List(List(1, 2, 3), List(4, 5, 6), List(7)))
(1 to 7).iterator grouped 3 toList
// Returns List(List(1, 2, 3), List(4, 5, 6))
(1 to 7).iterator grouped 3 withPartial false toList
// Returns List(List(1, 2, 3), List(4, 5, 6), List(7, 20, 25)
// Illustrating that withPadding's argument is by-name.
val it2 = Iterator.iterate(20)(_ + 5)
(1 to 7).iterator grouped 3 withPadding it2.next toList
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def indexOf[B >: String](elem: B): Int

Returns the index of the first occurrence of the specified object in this iterable object.

Note: may not terminate for infinite iterators.

  • elem
    • element to search for.
  • returns
    • the index of the first occurrence of elem in the values produced by this iterator, or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def indexOf[B >: String](elem: B, from: Int): Int

Returns the index of the first occurrence of the specified object in this iterable object after or at some start index.

Note: may not terminate for infinite iterators.

  • elem
    • element to search for.
  • from
    • the start index
  • returns
    • the index >= from of the first occurrence of elem in the values produced by this iterator, or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def indexWhere(p: (String) ⇒ Boolean): Int

Returns the index of the first produced value satisfying a predicate, or -1.

Note: may not terminate for infinite iterators.

  • p
    • the predicate to test values
  • returns
    • the index of the first produced value satisfying p , or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def indexWhere(p: (String) ⇒ Boolean, from: Int): Int

Returns the index of the first produced value satisfying a predicate, or -1, after or at some start index.

Note: may not terminate for infinite iterators.

  • p
    • the predicate to test values
  • from
    • the start index
  • returns
    • the index >= from of the first produced value satisfying p , or -1 if such an element does not exist until the end of the iterator is reached.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on. Using it is undefined and subject to change.

(defined at scala.collection.Iterator)

def map[B](f: (String) ⇒ B): collection.Iterator[B]

Creates a new iterator that maps all produced values of this iterator to new values using a transformation function.

  • f
    • the transformation function
  • returns
    • a new iterator which transforms every value produced by this iterator by applying the function f to it.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def padTo[A1 >: String](len: Int, elem: A1): collection.Iterator[A1]

[use case]

Appends an element value to this iterator until a given target length is reached.

  • len
    • the target length
  • elem
    • the padding value
  • returns
    • a new iterator consisting of producing all values of this iterator, followed by the minimal number of occurrences of elem so that the number of produced values is at least len .
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def partition(p: (String) ⇒ Boolean): (collection.Iterator[String], collection.Iterator[String])

Partitions this iterator in two iterators according to a predicate.

  • p
    • the predicate on which to partition
  • returns
    • a pair of iterators: the iterator that satisfies the predicate p and the iterator that does not. The relative order of the elements in the resulting iterators is the same as in the original iterator.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterators that were returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterators as well.

(defined at scala.collection.Iterator)

def patch[B >: String](from: Int, patchElems: collection.Iterator[B], replaced: Int): collection.Iterator[B]

Returns this iterator with patched values. Patching at negative indices is the same as patching starting at 0. Patching at indices at or larger than the length of the original iterator appends the patch to the end. If more values are replaced than actually exist, the excess is ignored.

  • from
    • The start index from which to patch
  • patchElems
    • The iterator of patch values
  • replaced
    • The number of values in the original iterator that are replaced by the patch.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, as well as the one passed as a parameter, and use only the iterator that was returned. Using the old iterators is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def sameElements(that: collection.Iterator[_]): Boolean

Tests if another iterator produces the same values as this one.

Note: will not terminate for infinite iterators.

  • that
    • the other iterator
  • returns
    • true , if both iterators produce the same elements in the same order, false otherwise.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, as well as the one passed as parameter. Using the old iterators is undefined and subject to change.

(defined at scala.collection.Iterator)

def scanLeft[B](z: B)(op: (B, String) ⇒ B): collection.Iterator[B]

Produces a collection containing cumulative results of applying the operator going left to right.

Note: will not terminate for infinite iterators.

Note: might return different results for different runs, unless the underlying collection type is ordered.

  • B
    • the type of the elements in the resulting collection
  • z
    • the initial value
  • op
    • the binary operator applied to the intermediate result and the element
  • returns
    • iterator with intermediate results
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def scanRight[B](z: B)(op: (String, B) ⇒ B): collection.Iterator[B]

Produces a collection containing cumulative results of applying the operator going right to left. The head of the collection is the last cumulative result.

Note: will not terminate for infinite iterators.

Note: might return different results for different runs, unless the underlying collection type is ordered.

  • B
    • the type of the elements in the resulting collection
  • z
    • the initial value
  • op
    • the binary operator applied to the intermediate result and the element
  • returns
    • iterator with intermediate results
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

Example:

Iterator(1, 2, 3, 4).scanRight(0)(_ + _).toList == List(10, 9, 7, 4, 0)

(defined at scala.collection.Iterator)

def seq: collection.Iterator[String]

A version of this collection with all of the operations implemented sequentially (i.e., in a single-threaded manner).

This method returns a reference to this collection. In parallel collections, it is redefined to return a sequential implementation of this collection. In both cases, it has O(1) complexity.

  • returns
    • a sequential view of the collection.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def slice(from: Int, until: Int): collection.Iterator[String]

Creates an iterator returning an interval of the values produced by this iterator.

  • from
    • the index of the first element in this iterator which forms part of the slice. If negative, the slice starts at zero.
  • until
    • the index of the first element following the slice. If negative, the slice is empty.
  • returns
    • an iterator which advances this iterator past the first from elements using drop , and then takes until - from elements, using take .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def sliceIterator(from: Int, until: Int): collection.Iterator[String]

Creates an optionally bounded slice, unbounded if until is negative.

  • Attributes
    • protected
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def sliding[B >: String](size: Int, step: Int = 1): GroupedIterator[B]

Returns an iterator which presents a “sliding window” view of another iterator. The first argument is the window size, and the second is how far to advance the window on each iteration; defaults to 1 . Example usages:

// Returns List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))
(1 to 5).iterator.sliding(3).toList
// Returns List(List(1, 2, 3, 4), List(4, 5))
(1 to 5).iterator.sliding(4, 3).toList
// Returns List(List(1, 2, 3, 4))
(1 to 5).iterator.sliding(4, 3).withPartial(false).toList
// Returns List(List(1, 2, 3, 4), List(4, 5, 20, 25))
// Illustrating that withPadding's argument is by-name.
val it2 = Iterator.iterate(20)(_ + 5)
(1 to 5).iterator.sliding(4, 3).withPadding(it2.next).toList
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def span(p: (String) ⇒ Boolean): (collection.Iterator[String], collection.Iterator[String])

Splits this Iterator into a prefix/suffix pair according to a predicate.

  • p
    • the test predicate
  • returns
    • a pair of Iterators consisting of the longest prefix of this whose elements all satisfy p , and the rest of the Iterator.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterators that were returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterators as well.

(defined at scala.collection.Iterator)

def take(n: Int): collection.Iterator[String]

Selects first n values of this iterator.

  • n
    • the number of values to take
  • returns
    • an iterator producing only the first n values of this iterator, or else the whole iterator, if it produces fewer than n values.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def takeWhile(p: (String) ⇒ Boolean): collection.Iterator[String]

Takes longest prefix of values produced by this iterator that satisfy a predicate.

  • p
    • The predicate used to test elements.
  • returns
    • An iterator returning the values produced by this iterator, until this iterator produces a value that does not satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def toIterator: collection.Iterator[String]

Returns an Iterator over the elements in this traversable or iterator. Will return the same Iterator if this instance is already an Iterator.

Note: will not terminate for infinite iterators.

  • returns
    • an Iterator containing all elements of this traversable or iterator.
  • Definition Classes
    • Iterator → GenTraversableOnce

(defined at scala.collection.Iterator)

def toStream: collection.immutable.Stream[String]

Converts this traversable or iterator to a stream.

  • returns
    • a stream containing all elements of this traversable or iterator.
  • Definition Classes
    • Iterator → GenTraversableOnce

(defined at scala.collection.Iterator)

def toTraversable: collection.Traversable[String]

Converts this traversable or iterator to an unspecified Traversable. Will return the same collection if this instance is already Traversable.

Note: will not terminate for infinite iterators.

  • returns
    • a Traversable containing all elements of this traversable or iterator.
  • Definition Classes
    • Iterator → TraversableOnce → GenTraversableOnce

(defined at scala.collection.Iterator)

def withFilter(p: (String) ⇒ Boolean): collection.Iterator[String]

Creates an iterator over all the elements of this iterator that satisfy the predicate p . The order of the elements is preserved.

Note: withFilter is the same as filter on iterators. It exists so that for-expressions with filters work over iterators.

  • p
    • the predicate used to test values.
  • returns
    • an iterator which produces those values of this iterator which satisfy the predicate p .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def zipAll[B, A1 >: String, B1 >: B](that: collection.Iterator[B], thisElem: A1, thatElem: B1): collection.Iterator[(A1, B1)]

[use case]

Creates an iterator formed from this iterator and another iterator by combining corresponding elements in pairs. If one of the two iterators is shorter than the other, placeholder elements are used to extend the shorter iterator to the length of the longer.

  • that
    • iterator that may have a different length as the self iterator.
  • thisElem
    • element thisElem is used to fill up the resulting iterator if the self iterator is shorter than that
  • thatElem
    • element thatElem is used to fill up the resulting iterator if that is shorter than the self iterator
  • returns
    • a new iterator containing pairs consisting of corresponding values of this iterator and that . The length of the returned iterator is the maximum of the lengths of this iterator and that . If this iterator is shorter than that , thisElem values are used to pad the result. If that is shorter than this iterator, thatElem values are used to pad the result.
  • Definition Classes
    • Iterator

(defined at scala.collection.Iterator)

def zipWithIndex: collection.Iterator[(String, Int)]

Creates an iterator that pairs each element produced by this iterator with its index, counting from 0.

  • returns
    • a new iterator containing pairs consisting of corresponding elements of this iterator and their indices.
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, and use only the iterator that was returned. Using the old iterator is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

def zip[B](that: collection.Iterator[B]): collection.Iterator[(String, B)]

Creates an iterator formed from this iterator and another iterator by combining corresponding values in pairs. If one of the two iterators is longer than the other, its remaining elements are ignored.

  • that
    • The iterator providing the second half of each result pair
  • returns
    • a new iterator containing pairs consisting of corresponding elements of this iterator and that . The number of elements returned by the new iterator is the minimum of the number of elements returned by this iterator and that .
  • Definition Classes
    • Iterator
  • Note
    • Reuse: After calling this method, one should discard the iterator it was called on, as well as the one passed as a parameter, and use only the iterator that was returned. Using the old iterators is undefined, subject to change, and may result in changes to the new iterator as well.

(defined at scala.collection.Iterator)

Value Members From scala.collection.TraversableOnce

def /:[B](z: B)(op: (B, String) ⇒ B): B

Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.

Note: /: is alternate syntax for foldLeft ; z /: xs is the same as xs foldLeft z .

Examples:

Note that the folding function used to compute b is equivalent to that used to compute c.

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = (5 /: a)(_+_)
b: Int = 15

scala> val c = (5 /: a)((x,y) => x + y)
c: Int = 15

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • z
    • the start value.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going left to right with the start value z on the left:
    op(...op(op(z, x_1), x_2), ..., x_n)
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def :\[B](z: B)(op: (String, B) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator and a start value, going right to left.

Note: :\ is alternate syntax for foldRight ; xs :\ z is the same as xs foldRight z .

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

Examples:

Note that the folding function used to compute b is equivalent to that used to compute c.

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = (a :\ 5)(_+_)
b: Int = 15

scala> val c = (a :\ 5)((x,y) => x + y)
c: Int = 15
  • B
    • the result type of the binary operator.
  • z
    • the start value
  • op
    • the binary operator
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going right to left with the start value z on the right:
    op(x_1, op(x_2, ... op(x_n, z)...))
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def addString(b: StringBuilder): StringBuilder

Appends all elements of this traversable or iterator to a string builder. The written text consists of the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator without any separator string.

Example:

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> val h = a.addString(b)
h: StringBuilder = 1234
  • b
    • the string builder to which elements are appended.
  • returns
    • the string builder b to which elements were appended.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def addString(b: StringBuilder, sep: String): StringBuilder

Appends all elements of this traversable or iterator to a string builder using a separator string. The written text consists of the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator, separated by the string sep .

Example:

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> a.addString(b, ", ")
res0: StringBuilder = 1, 2, 3, 4
  • b
    • the string builder to which elements are appended.
  • sep
    • the separator string.
  • returns
    • the string builder b to which elements were appended.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder

Appends all elements of this traversable or iterator to a string builder using start, end, and separator strings. The written text begins with the string start and ends with the string end . Inside, the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator are separated by the string sep .

Example:

scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)

scala> val b = new StringBuilder()
b: StringBuilder =

scala> a.addString(b , "List(" , ", " , ")")
res5: StringBuilder = List(1, 2, 3, 4)
  • b
    • the string builder to which elements are appended.
  • start
    • the starting string.
  • sep
    • the separator string.
  • end
    • the ending string.
  • returns
    • the string builder b to which elements were appended.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def aggregate[B](z: ⇒ B)(seqop: (B, String) ⇒ B, combop: (B, B) ⇒ B): B

Aggregates the results of applying an operator to subsequent elements.

This is a more general form of fold and reduce . It is similar to foldLeft in that it doesn’t require the result to be a supertype of the element type. In addition, it allows parallel collections to be processed in chunks, and then combines the intermediate results.

aggregate splits the traversable or iterator into partitions and processes each partition by sequentially applying seqop , starting with z (like foldLeft ). Those intermediate results are then combined by using combop (like fold ). The implementation of this operation may operate on an arbitrary number of collection partitions (even 1), so combop may be invoked an arbitrary number of times (even 0).

As an example, consider summing up the integer values of a list of chars. The initial value for the sum is 0. First, seqop transforms each input character to an Int and adds it to the sum (of the partition). Then, combop just needs to sum up the intermediate results of the partitions:

List('a', 'b', 'c').aggregate(0)({ (sum, ch) => sum + ch.toInt }, { (p1, p2) => p1 + p2 })
  • B
    • the type of accumulated results
  • z
    • the initial value for the accumulated result of the partition - this will typically be the neutral element for the seqop operator (e.g. Nil for list concatenation or 0 for summation) and may be evaluated more than once
  • seqop
    • an operator used to accumulate results within a partition
  • combop
    • an associative operator used to combine results from different partitions
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def collectFirst[B](pf: PartialFunction[String, B]): Option[B]

Finds the first element of the traversable or iterator for which the given partial function is defined, and applies the partial function to it.

Note: may not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered.

  • pf
    • the partial function
  • returns
    • an option value containing pf applied to the first value for which it is defined, or None if none exists.
  • Definition Classes
    • TraversableOnce

Example:

Seq("a", 1, 5L).collectFirst({ case x: Int => x*10 }) = Some(10)

(defined at scala.collection.TraversableOnce)

def copyToArray[B >: String](xs: Array[B]): Unit

[use case]

Copies the elements of this traversable or iterator to an array. Fills the given array xs with values of this traversable or iterator. Copying will stop once either the end of the current traversable or iterator is reached, or the end of the target array is reached.

Note: will not terminate for infinite iterators.

  • xs
    • the array to fill.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def copyToArray[B >: String](xs: Array[B], start: Int): Unit

[use case]

Copies the elements of this traversable or iterator to an array. Fills the given array xs with values of this traversable or iterator, beginning at index start . Copying will stop once either the end of the current traversable or iterator is reached, or the end of the target array is reached.

Note: will not terminate for infinite iterators.

  • xs
    • the array to fill.
  • start
    • the starting index.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def copyToBuffer[B >: String](dest: Buffer[B]): Unit

Copies all elements of this traversable or iterator to a buffer.

Note: will not terminate for infinite-sized collections.

  • dest
    • The buffer to which elements are copied.
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def count(p: (String) ⇒ Boolean): Int

Counts the number of elements in the traversable or iterator which satisfy a predicate.

  • p
    • the predicate used to test elements.
  • returns
    • the number of elements satisfying the predicate p .
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def foldLeft[B](z: B)(op: (B, String) ⇒ B): B

Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • z
    • the start value.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going left to right with the start value z on the left:
    op(...op(z, x_1), x_2, ..., x_n)
    
where `x1, ..., xn` are the elements of this traversable or iterator.
Returns `z` if this traversable or iterator is empty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def foldRight[B](z: B)(op: (String, B) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator and a start value, going right to left.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • z
    • the start value.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going right to left with the start value z on the right:
    op(x_1, op(x_2, ... op(x_n, z)...))
    
where `x1, ..., xn` are the elements of this traversable or iterator.
Returns `z` if this traversable or iterator is empty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def fold[A1 >: String](z: A1)(op: (A1, A1) ⇒ A1): A1

Folds the elements of this traversable or iterator using the specified associative binary operator.

The order in which operations are performed on elements is unspecified and may be nondeterministic.

Note: will not terminate for infinite-sized collections.

  • A1
    • a type parameter for the binary operator, a supertype of A .
  • z
    • a neutral element for the fold operation; may be added to the result an arbitrary number of times, and must not change the result (e.g., Nil for list concatenation, 0 for addition, or 1 for multiplication).
  • op
    • a binary operator that must be associative.
  • returns
    • the result of applying the fold operator op between all the elements and z , or z if this traversable or iterator is empty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def maxBy[B](f: (String) ⇒ B)(implicit cmp: Ordering[B]): String

[use case]

Finds the first element which yields the largest value measured by function f.

  • B
    • The result type of the function f.
  • f
    • The measuring function.
  • returns
    • the first element of this traversable or iterator with the largest value measured by function f.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def minBy[B](f: (String) ⇒ B)(implicit cmp: Ordering[B]): String

[use case]

Finds the first element which yields the smallest value measured by function f.

  • B
    • The result type of the function f.
  • f
    • The measuring function.
  • returns
    • the first element of this traversable or iterator with the smallest value measured by function f.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def mkString(sep: String): String

Displays all elements of this traversable or iterator in a string using a separator string.

  • sep
    • the separator string.
  • returns
    • a string representation of this traversable or iterator. In the resulting string the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator are separated by the string sep .
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

Example:

List(1, 2, 3).mkString("|") = "1|2|3"

(defined at scala.collection.TraversableOnce)

def mkString(start: String, sep: String, end: String): String

Displays all elements of this traversable or iterator in a string using start, end, and separator strings.

  • start
    • the starting string.
  • sep
    • the separator string.
  • end
    • the ending string.
  • returns
    • a string representation of this traversable or iterator. The resulting string begins with the string start and ends with the string end . Inside, the string representations (w.r.t. the method toString ) of all elements of this traversable or iterator are separated by the string sep .
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

Example:

List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"

(defined at scala.collection.TraversableOnce)

def reduceLeftOption[B >: String](op: (B, String) ⇒ B): Option[B]

Optionally applies a binary operator to all elements of this traversable or iterator, going left to right.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • an option value containing the result of reduceLeft(op) if this traversable or iterator is nonempty, None otherwise.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def reduceLeft[B >: String](op: (B, String) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator, going left to right.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going left to right:
    op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce
  • Exceptions thrown
    • UnsupportedOperationException if this traversable or iterator is empty.

(defined at scala.collection.TraversableOnce)

def reduceOption[A1 >: String](op: (A1, A1) ⇒ A1): Option[A1]

Reduces the elements of this traversable or iterator, if any, using the specified associative binary operator.

The order in which operations are performed on elements is unspecified and may be nondeterministic.

  • A1
    • A type parameter for the binary operator, a supertype of A .
  • op
    • A binary operator that must be associative.
  • returns
    • An option value containing result of applying reduce operator op between all the elements if the collection is nonempty, and None otherwise.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def reduceRightOption[B >: String](op: (String, B) ⇒ B): Option[B]

Optionally applies a binary operator to all elements of this traversable or iterator, going right to left.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • an option value containing the result of reduceRight(op) if this traversable or iterator is nonempty, None otherwise.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def reduceRight[B >: String](op: (String, B) ⇒ B): B

Applies a binary operator to all elements of this traversable or iterator, going right to left.

Note: will not terminate for infinite-sized collections.

Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.

  • B
    • the result type of the binary operator.
  • op
    • the binary operator.
  • returns
    • the result of inserting op between consecutive elements of this traversable or iterator, going right to left:
    op(x_1, op(x_2, ..., op(x_{n-1}, x_n)...))
    
where `x1, ..., xn` are the elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce
  • Exceptions thrown
    • UnsupportedOperationException if this traversable or iterator is empty.

(defined at scala.collection.TraversableOnce)

def reduce[A1 >: String](op: (A1, A1) ⇒ A1): A1

Reduces the elements of this traversable or iterator using the specified associative binary operator.

The order in which operations are performed on elements is unspecified and may be nondeterministic.

  • A1
    • A type parameter for the binary operator, a supertype of A .
  • op
    • A binary operator that must be associative.
  • returns
    • The result of applying reduce operator op between all the elements if the traversable or iterator is nonempty.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce
  • Exceptions thrown
    • UnsupportedOperationException if this traversable or iterator is empty.

(defined at scala.collection.TraversableOnce)

def reversed: List[String]

  • Attributes
    • protected[this]
  • Definition Classes
    • TraversableOnce

(defined at scala.collection.TraversableOnce)

def toBuffer[B >: String]: Buffer[B]

Uses the contents of this traversable or iterator to create a new mutable buffer.

Note: will not terminate for infinite-sized collections.

  • returns
    • a buffer containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toIndexedSeq: collection.immutable.IndexedSeq[String]

Converts this traversable or iterator to an indexed sequence.

Note: will not terminate for infinite-sized collections.

  • returns
    • an indexed sequence containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toIterable: collection.Iterable[String]

Converts this traversable or iterator to an iterable collection. Note that the choice of target Iterable is lazy in this default implementation as this TraversableOnce may be lazy and unevaluated (i.e. it may be an iterator which is only traversable once).

Note: will not terminate for infinite-sized collections.

  • returns
    • an Iterable containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toList: List[String]

Converts this traversable or iterator to a list.

Note: will not terminate for infinite-sized collections.

  • returns
    • a list containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toMap[T, U](implicit ev: <:<[String, (T, U)]): Map[T, U]

[use case]

Converts this traversable or iterator to a map. This method is unavailable unless the elements are members of Tuple2, each ((T, U)) becoming a key-value pair in the map. Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.

Note: will not terminate for infinite iterators.

  • returns
    • a map of type immutable.Map[T, U] containing all key/value pairs of type (T, U) of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toSeq: collection.Seq[String]

Converts this traversable or iterator to a sequence. As with toIterable , it’s lazy in this default implementation, as this TraversableOnce may be lazy and unevaluated.

Note: will not terminate for infinite-sized collections.

  • returns
    • a sequence containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toSet[B >: String]: Set[B]

Converts this traversable or iterator to a set.

Note: will not terminate for infinite-sized collections.

  • returns
    • a set containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

def toVector: Vector[String]

Converts this traversable or iterator to a Vector.

Note: will not terminate for infinite-sized collections.

  • returns
    • a vector containing all elements of this traversable or iterator.
  • Definition Classes
    • TraversableOnce → GenTraversableOnce

(defined at scala.collection.TraversableOnce)

Value Members From scala.util.matching.Regex.MatchData

def after(i: Int): CharSequence

The char sequence after last character of match in group i , or null if nothing was matched for that group.

  • Definition Classes
    • MatchData

(defined at scala.util.matching.Regex.MatchData)

def before(i: Int): CharSequence

The char sequence before first character of match in group i , or null if nothing was matched for that group.

  • Definition Classes
    • MatchData

(defined at scala.util.matching.Regex.MatchData)

def group(i: Int): String

The matched string in group i , or null if nothing was matched.

  • Definition Classes
    • MatchData

(defined at scala.util.matching.Regex.MatchData)

def group(id: String): String

Returns the group with given name.

  • id
    • The group name
  • returns
    • The requested group
  • Definition Classes
    • MatchData
  • Exceptions thrown
    • NoSuchElementException if the requested group name is not defined

(defined at scala.util.matching.Regex.MatchData)

Instance Constructors From scala.util.matching.Regex.MatchIterator

new MatchIterator(source: CharSequence, regex: Regex, groupNames: Seq[String])

(defined at scala.util.matching.Regex.MatchIterator)

Value Members From scala.util.matching.Regex.MatchIterator

def end(i: Int): Int

The index following the last matched character in group i .

  • Definition Classes
    • MatchIterator → MatchData

(defined at scala.util.matching.Regex.MatchIterator)

def matchData: Iterator[Match]

Convert to an iterator that yields MatchData elements instead of Strings.

(defined at scala.util.matching.Regex.MatchIterator)

val matcher: Matcher

  • Attributes
    • protected[scala.util.matching.Regex]

(defined at scala.util.matching.Regex.MatchIterator)

val regex: Regex

(defined at scala.util.matching.Regex.MatchIterator)

def start(i: Int): Int

The index of the first matched character in group i .

  • Definition Classes
    • MatchIterator → MatchData (defined at scala.util.matching.Regex.MatchIterator)

Full Source:

/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2007-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

/**
 * This package is concerned with regular expression (regex) matching against strings,
 * with the main goal of pulling out information from those matches, or replacing
 * them with something else.
 *
 * There are four classes and three objects, with most of them being members of
 * Regex companion object. [[scala.util.matching.Regex]] is the class users instantiate
 * to do regular expression matching.
 *
 * The remaining classes and objects in the package are used in the following way:
 *
 * * The companion object to [[scala.util.matching.Regex]] just contains the other members.
 * * [[scala.util.matching.Regex.Match]] makes more information about a match available.
 * * [[scala.util.matching.Regex.MatchIterator]] is used to iterate over multiple matches.
 * * [[scala.util.matching.Regex.MatchData]] is just a base trait for the above classes.
 * * [[scala.util.matching.Regex.Groups]] extracts group from a [[scala.util.matching.Regex.Match]]
 *   without recomputing the match.
 * * [[scala.util.matching.Regex.Match]] converts a [[scala.util.matching.Regex.Match]]
 *   into a [[java.lang.String]].
 *
 */
package scala.util.matching

import scala.collection.AbstractIterator
import java.util.regex.{ Pattern, Matcher }

/** A regular expression is used to determine whether a string matches a pattern
 *  and, if it does, to extract or transform the parts that match.
 *
 *  This class delegates to the [[java.util.regex]] package of the Java Platform.
 *  See the documentation for [[java.util.regex.Pattern]] for details about
 *  the regular expression syntax for pattern strings.
 *
 *  An instance of `Regex` represents a compiled regular expression pattern.
 *  Since compilation is expensive, frequently used `Regex`es should be constructed
 *  once, outside of loops and perhaps in a companion object.
 *
 *  The canonical way to create a `Regex` is by using the method `r`, provided
 *  implicitly for strings:
 *
 *  {{{
 *  val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
 *  }}}
 *
 *  Since escapes are not processed in multi-line string literals, using triple quotes
 *  avoids having to escape the backslash character, so that `"\\d"` can be written `"""\d"""`.
 *
 *  To extract the capturing groups when a `Regex` is matched, use it as
 *  an extractor in a pattern match:
 *
 *  {{{
 *  "2004-01-20" match {
 *    case date(year, month, day) => s"$year was a good year for PLs."
 *  }
 *  }}}
 *
 *  To check only whether the `Regex` matches, ignoring any groups,
 *  use a sequence wildcard:
 *
 *  {{{
 *  "2004-01-20" match {
 *    case date(_*) => "It's a date!"
 *  }
 *  }}}
 *
 *  That works because a `Regex` extractor produces a sequence of strings.
 *  Extracting only the year from a date could also be expressed with
 *  a sequence wildcard:
 *
 *  {{{
 *  "2004-01-20" match {
 *    case date(year, _*) => s"$year was a good year for PLs."
 *  }
 *  }}}
 *
 *  In a pattern match, `Regex` normally matches the entire input.
 *  However, an unanchored `Regex` finds the pattern anywhere
 *  in the input.
 *
 *  {{{
 *  val embeddedDate = date.unanchored
 *  "Date: 2004-01-20 17:25:18 GMT (10 years, 28 weeks, 5 days, 17 hours and 51 minutes ago)" match {
 *    case embeddedDate("2004", "01", "20") => "A Scala is born."
 *  }
 *  }}}
 *
 *  To find or replace matches of the pattern, use the various find and replace methods.
 *  There is a flavor of each method that produces matched strings and
 *  another that produces `Match` objects.
 *
 *  For example, pattern matching with an unanchored `Regex`, as in the previous example,
 *  is the same as using `findFirstMatchIn`, except that the findFirst methods return an `Option`,
 *  or `None` for no match:
 *
 *  {{{
 *  val dates = "Important dates in history: 2004-01-20, 1958-09-05, 2010-10-06, 2011-07-15"
 *  val firstDate = date findFirstIn dates getOrElse "No date found."
 *  val firstYear = for (m <- date findFirstMatchIn dates) yield m group 1
 *  }}}
 *
 *  To find all matches:
 *
 *  {{{
 *  val allYears = for (m <- date findAllMatchIn dates) yield m group 1
 *  }}}
 *
 *  But `findAllIn` returns a special iterator of strings that can be queried for the `MatchData`
 *  of the last match:
 *
 *  {{{
 *  val mi = date findAllIn dates
 *  val oldies = mi filter (_ => (mi group 1).toInt < 1960) map (s => s"$s: An oldie but goodie.")
 *  }}}
 *
 *  Note that `findAllIn` finds matches that don't overlap. (See [[findAllIn]] for more examples.)
 *
 *  {{{
 *  val num = """(\d+)""".r
 *  val all = (num findAllIn "123").toList  // List("123"), not List("123", "23", "3")
 *  }}}
 *
 *  Text replacement can be performed unconditionally or as a function of the current match:
 *
 *  {{{
 *  val redacted    = date replaceAllIn (dates, "XXXX-XX-XX")
 *  val yearsOnly   = date replaceAllIn (dates, m => m group 1)
 *  val months      = (0 to 11) map { i => val c = Calendar.getInstance; c.set(2014, i, 1); f"$c%tb" }
 *  val reformatted = date replaceAllIn (dates, _ match { case date(y,m,d) => f"${months(m.toInt - 1)} $d, $y" })
 *  }}}
 *
 *  Pattern matching the `Match` against the `Regex` that created it does not reapply the `Regex`.
 *  In the expression for `reformatted`, each `date` match is computed once. But it is possible to apply a
 *  `Regex` to a `Match` resulting from a different pattern:
 *
 *  {{{
 *  val docSpree = """2011(?:-\d{2}){2}""".r
 *  val docView  = date replaceAllIn (dates, _ match {
 *    case docSpree() => "Historic doc spree!"
 *    case _          => "Something else happened"
 *  })
 *  }}}
 *
 *  @see [[java.util.regex.Pattern]]
 *
 *  @author  Thibaud Hottelier
 *  @author  Philipp Haller
 *  @author  Martin Odersky
 *  @version 1.1, 29/01/2008
 *
 *  @param pattern    The compiled pattern
 *  @param groupNames A mapping from names to indices in capture groups
 *
 *  @define replacementString
 *  In the replacement String, a dollar sign (`$`) followed by a number will be
 *  interpreted as a reference to a group in the matched pattern, with numbers
 *  1 through 9 corresponding to the first nine groups, and 0 standing for the
 *  whole match. Any other character is an error. The backslash (`\`) character
 *  will be interpreted as an escape character and can be used to escape the
 *  dollar sign. Use `Regex.quoteReplacement` to escape these characters.
 */
@SerialVersionUID(-2094783597747625537L)
class Regex private[matching](val pattern: Pattern, groupNames: String*) extends Serializable {
  outer =>

  import Regex._

  /** Compile a regular expression, supplied as a string, into a pattern that
   *  can be matched against inputs.
   *
   *  If group names are supplied, they can be used this way:
   *
   *  {{{
   *  val namedDate  = new Regex("""(\d\d\d\d)-(\d\d)-(\d\d)""", "year", "month", "day")
   *  val namedYears = for (m <- namedDate findAllMatchIn dates) yield m group "year"
   *  }}}
   *
   *  This constructor does not support options as flags, which must be
   *  supplied as inline flags in the pattern string: `(?idmsux-idmsux)`.
   *
   *  @param regex      The regular expression to compile.
   *  @param groupNames Names of capturing groups.
   */
  def this(regex: String, groupNames: String*) = this(Pattern.compile(regex), groupNames: _*)

  /** Tries to match a [[java.lang.CharSequence]].
   *
   *  If the match succeeds, the result is a list of the matching
   *  groups (or a `null` element if a group did not match any input).
   *  If the pattern specifies no groups, then the result will be an empty list
   *  on a successful match.
   *
   *  This method attempts to match the entire input by default; to find the next
   *  matching subsequence, use an unanchored `Regex`.
   *
   *  For example:
   *
   *  {{{
   *  val p1 = "ab*c".r
   *  val p1Matches = "abbbc" match {
   *    case p1() => true               // no groups
   *    case _    => false
   *  }
   *  val p2 = "a(b*)c".r
   *  val p2Matches = "abbbc" match {
   *    case p2(_*) => true             // any groups
   *    case _      => false
   *  }
   *  val numberOfB = "abbbc" match {
   *    case p2(b) => Some(b.length)    // one group
   *    case _     => None
   *  }
   *  val p3 = "b*".r.unanchored
   *  val p3Matches = "abbbc" match {
   *    case p3() => true               // find the b's
   *    case _    => false
   *  }
   *  val p4 = "a(b*)(c+)".r
   *  val p4Matches = "abbbcc" match {
   *    case p4(_*) => true             // multiple groups
   *    case _      => false
   *  }
   *  val allGroups = "abbbcc" match {
   *    case p4(all @ _*) => all mkString "/" // "bbb/cc"
   *    case _            => ""
   *  }
   *  val cGroup = "abbbcc" match {
   *    case p4(_, c) => c
   *    case _        => ""
   *  }
   *  }}}
   *
   *  @param  s     The string to match
   *  @return       The matches
   */
  def unapplySeq(s: CharSequence): Option[List[String]] = s match {
    case null => None
    case _    =>
      val m = pattern matcher s
      if (runMatcher(m)) Some((1 to m.groupCount).toList map m.group)
      else None
  }

  /** Tries to match the String representation of a [[scala.Char]].
   *
   *  If the match succeeds, the result is the first matching
   *  group if any groups are defined, or an empty Sequence otherwise.
   *
   *  For example:
   *
   *  {{{
   *  val cat = "cat"
   *  // the case must consume the group to match
   *  val r = """(\p{Lower})""".r
   *  cat(0) match { case r(x) => true }
   *  cat(0) match { case r(_) => true }
   *  cat(0) match { case r(_*) => true }
   *  cat(0) match { case r() => true }     // no match
   *
   *  // there is no group to extract
   *  val r = """\p{Lower}""".r
   *  cat(0) match { case r(x) => true }    // no match
   *  cat(0) match { case r(_) => true }    // no match
   *  cat(0) match { case r(_*) => true }   // matches
   *  cat(0) match { case r() => true }     // matches
   *
   *  // even if there are multiple groups, only one is returned
   *  val r = """((.))""".r
   *  cat(0) match { case r(_) => true }    // matches
   *  cat(0) match { case r(_,_) => true }  // no match
   *  }}}
   *
   *  @param  c     The Char to match
   *  @return       The match
   */
  def unapplySeq(c: Char): Option[List[Char]] = {
    val m = pattern matcher c.toString
    if (runMatcher(m)) {
      if (m.groupCount > 0) Some((m group 1).toList) else Some(Nil)
    } else None
  }

  /** Tries to match on a [[scala.util.matching.Regex.Match]].
   *
   *  A previously failed match results in None.
   *
   *  If a successful match was made against the current pattern, then that result is used.
   *
   *  Otherwise, this Regex is applied to the previously matched input,
   *  and the result of that match is used.
   */
  def unapplySeq(m: Match): Option[List[String]] =
    if (m == null || m.matched == null) None
    else if (m.matcher.pattern == this.pattern) Some((1 to m.groupCount).toList map m.group)
    else unapplySeq(m.matched)

  /** Tries to match target.
   *  @param target The string to match
   *  @return       The matches
   */
  @deprecated("Extracting a match result from anything but a CharSequence or Match is deprecated", "2.11.0")
  def unapplySeq(target: Any): Option[List[String]] = target match {
    case s: CharSequence =>
      val m = pattern matcher s
      if (runMatcher(m)) Some((1 to m.groupCount).toList map m.group)
      else None
    case m: Match => unapplySeq(m.matched)
    case _ => None
  }

  //  @see UnanchoredRegex
  protected def runMatcher(m: Matcher) = m.matches()

  /** Return all non-overlapping matches of this `Regex` in the given character 
   *  sequence as a [[scala.util.matching.Regex.MatchIterator]],
   *  which is a special [[scala.collection.Iterator]] that returns the
   *  matched strings but can also be queried for more data about the last match,
   *  such as capturing groups and start position.
   * 
   *  A `MatchIterator` can also be converted into an iterator
   *  that returns objects of type [[scala.util.matching.Regex.Match]],
   *  such as is normally returned by `findAllMatchIn`.
   * 
   *  Where potential matches overlap, the first possible match is returned,
   *  followed by the next match that follows the input consumed by the
   *  first match:
   *
   *  {{{
   *  val hat  = "hat[^a]+".r
   *  val hathaway = "hathatthattthatttt"
   *  val hats = (hat findAllIn hathaway).toList                     // List(hath, hattth)
   *  val pos  = (hat findAllMatchIn hathaway map (_.start)).toList  // List(0, 7)
   *  }}}
   *
   *  To return overlapping matches, it is possible to formulate a regular expression
   *  with lookahead (`?=`) that does not consume the overlapping region.
   *
   *  {{{
   *  val madhatter = "(h)(?=(at[^a]+))".r
   *  val madhats   = (madhatter findAllMatchIn hathaway map {
   *    case madhatter(x,y) => s"$x$y"
   *  }).toList                                       // List(hath, hatth, hattth, hatttt)
   *  }}}
   *
   *  Attempting to retrieve match information before performing the first match
   *  or after exhausting the iterator results in [[java.lang.IllegalStateException]].
   *  See [[scala.util.matching.Regex.MatchIterator]] for details.
   *
   *  @param source The text to match against.
   *  @return       A [[scala.util.matching.Regex.MatchIterator]] of matched substrings.
   *  @example      {{{for (words <- """\w+""".r findAllIn "A simple example.") yield words}}}
   */
  def findAllIn(source: CharSequence) = new Regex.MatchIterator(source, this, groupNames)

  /** Return all non-overlapping matches of this regexp in given character sequence as a
   *  [[scala.collection.Iterator]] of [[scala.util.matching.Regex.Match]].
   *
   *  @param source The text to match against.
   *  @return       A [[scala.collection.Iterator]] of [[scala.util.matching.Regex.Match]] for all matches.
   *  @example      {{{for (words <- """\w+""".r findAllMatchIn "A simple example.") yield words.start}}}
   */
  def findAllMatchIn(source: CharSequence): Iterator[Match] = {
    val matchIterator = findAllIn(source)
    new Iterator[Match] {
      def hasNext = matchIterator.hasNext
      def next: Match = {
        matchIterator.next()
        new Match(matchIterator.source, matchIterator.matcher, matchIterator.groupNames).force
      }
    }
  }

  /** Return an optional first matching string of this `Regex` in the given character sequence,
   *  or None if there is no match.
   *
   *  @param source The text to match against.
   *  @return       An [[scala.Option]] of the first matching string in the text.
   *  @example      {{{"""\w+""".r findFirstIn "A simple example." foreach println // prints "A"}}}
   */
  def findFirstIn(source: CharSequence): Option[String] = {
    val m = pattern.matcher(source)
    if (m.find) Some(m.group) else None
  }

  /** Return an optional first match of this `Regex` in the given character sequence,
   *  or None if it does not exist.
   *
   *  If the match is successful, the [[scala.util.matching.Regex.Match]] can be queried for
   *  more data.
   *
   *  @param source The text to match against.
   *  @return       A [[scala.Option]] of [[scala.util.matching.Regex.Match]] of the first matching string in the text.
   *  @example      {{{("""[a-z]""".r findFirstMatchIn "A simple example.") map (_.start) // returns Some(2), the index of the first match in the text}}}
   */
  def findFirstMatchIn(source: CharSequence): Option[Match] = {
    val m = pattern.matcher(source)
    if (m.find) Some(new Match(source, m, groupNames)) else None
  }

  /** Return an optional match of this `Regex` at the beginning of the
   *  given character sequence, or None if it matches no prefix
   *  of the character sequence.
   *
   *  Unlike `findFirstIn`, this method will only return a match at
   *  the beginning of the input.
   *
   *  @param source The text to match against.
   *  @return       A [[scala.Option]] of the matched prefix.
   *  @example      {{{"""\p{Lower}""".r findPrefixOf "A simple example." // returns None, since the text does not begin with a lowercase letter}}}
   */
  def findPrefixOf(source: CharSequence): Option[String] = {
    val m = pattern.matcher(source)
    if (m.lookingAt) Some(m.group) else None
  }

  /** Return an optional match of this `Regex` at the beginning of the
   *  given character sequence, or None if it matches no prefix
   *  of the character sequence.
   *
   *  Unlike `findFirstMatchIn`, this method will only return a match at
   *  the beginning of the input.
   *
   *  @param source The text to match against.
   *  @return       A [[scala.Option]] of the [[scala.util.matching.Regex.Match]] of the matched string.
   *  @example      {{{"""\w+""".r findPrefixMatchOf "A simple example." map (_.after) // returns Some(" simple example.")}}}
   */
  def findPrefixMatchOf(source: CharSequence): Option[Match] = {
    val m = pattern.matcher(source)
    if (m.lookingAt) Some(new Match(source, m, groupNames)) else None
  }

  /** Replaces all matches by a string.
   *
   *  $replacementString
   *
   *  @param target      The string to match
   *  @param replacement The string that will replace each match
   *  @return            The resulting string
   *  @example           {{{"""\d+""".r replaceAllIn ("July 15", "<NUMBER>") // returns "July <NUMBER>"}}}
   */
  def replaceAllIn(target: CharSequence, replacement: String): String = {
    val m = pattern.matcher(target)
    m.replaceAll(replacement)
  }

  /**
   * Replaces all matches using a replacer function. The replacer function takes a
   * [[scala.util.matching.Regex.Match]] so that extra information can be obtained
   * from the match. For example:
   *
   * {{{
   * import scala.util.matching.Regex
   * val datePattern = new Regex("""(\d\d\d\d)-(\d\d)-(\d\d)""", "year", "month", "day")
   * val text = "From 2011-07-15 to 2011-07-17"
   * val repl = datePattern replaceAllIn (text, m => s"${m group "month"}/${m group "day"}")
   * }}}
   *
   * $replacementString
   *
   * @param target      The string to match.
   * @param replacer    The function which maps a match to another string.
   * @return            The target string after replacements.
   */
  def replaceAllIn(target: CharSequence, replacer: Match => String): String = {
    val it = new Regex.MatchIterator(target, this, groupNames).replacementData
    it foreach (md => it replace replacer(md))
    it.replaced
  }

  /**
   * Replaces some of the matches using a replacer function that returns an [[scala.Option]].
   * The replacer function takes a [[scala.util.matching.Regex.Match]] so that extra
   * information can be obtained from the match. For example:
   *
   * {{{
   * import scala.util.matching.Regex._
   *
   * val vars = Map("x" -> "a var", "y" -> """some $ and \ signs""")
   * val text = "A text with variables %x, %y and %z."
   * val varPattern = """%(\w+)""".r
   * val mapper = (m: Match) => vars get (m group 1) map (quoteReplacement(_))
   * val repl = varPattern replaceSomeIn (text, mapper)
   * }}}
   *
   * $replacementString
   *
   * @param target      The string to match.
   * @param replacer    The function which optionally maps a match to another string.
   * @return            The target string after replacements.
   */
  def replaceSomeIn(target: CharSequence, replacer: Match => Option[String]): String = {
    val it = new Regex.MatchIterator(target, this, groupNames).replacementData
    for (matchdata <- it ; replacement <- replacer(matchdata))
      it replace replacement

    it.replaced
  }

  /** Replaces the first match by a string.
   *
   *  $replacementString
   *
   *  @param target      The string to match
   *  @param replacement The string that will replace the match
   *  @return            The resulting string
   */
  def replaceFirstIn(target: CharSequence, replacement: String): String = {
    val m = pattern.matcher(target)
    m.replaceFirst(replacement)
  }

  /** Splits the provided character sequence around matches of this regexp.
   *
   *  @param toSplit The character sequence to split
   *  @return        The array of strings computed by splitting the
   *                 input around matches of this regexp
   */
  def split(toSplit: CharSequence): Array[String] =
    pattern.split(toSplit)

  /** Create a new Regex with the same pattern, but no requirement that
   *  the entire String matches in extractor patterns.
   *
   *  Normally, matching on `date` behaves as though the pattern were
   *  enclosed in anchors, `"^pattern$"`.
   *
   *  The unanchored `Regex` behaves as though those anchors were removed.
   *
   *  Note that this method does not actually strip any matchers from the pattern.
   *
   *  Calling `anchored` returns the original `Regex`.
   *
   *  {{{
   *  val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r.unanchored
   *
   *  val date(year, month, day) = "Date 2011-07-15"                       // OK
   *
   *  val copyright: String = "Date of this document: 2011-07-15" match {
   *    case date(year, month, day) => s"Copyright $year"                  // OK
   *    case _                      => "No copyright"
   *  }
   *  }}}
   *
   *  @return        The new unanchored regex
   */
  def unanchored: UnanchoredRegex = new Regex(pattern, groupNames: _*) with UnanchoredRegex { override def anchored = outer }
  def anchored: Regex             = this

  def regex: String = pattern.pattern

  /** The string defining the regular expression */
  override def toString = regex
}

/** A [[Regex]] that finds the first match when used in a pattern match.
 *
 *  @see [[Regex#unanchored]]
 */
trait UnanchoredRegex extends Regex {
  override protected def runMatcher(m: Matcher) = m.find()
  override def unanchored = this
}

/** This object defines inner classes that describe
 *  regex matches and helper objects.
 */
object Regex {

  /** This class provides methods to access
   *  the details of a match.
   */
  trait MatchData {

    /** The source from which the match originated */
    val source: CharSequence

    /** The names of the groups, or an empty sequence if none defined */
    val groupNames: Seq[String]

    /** The number of capturing groups in the pattern.
     *  (For a given successful match, some of those groups may not have matched any input.)
     */
    def groupCount: Int

    /** The index of the first matched character, or -1 if nothing was matched */
    def start: Int

    /** The index of the first matched character in group `i`,
     *  or -1 if nothing was matched for that group.
     */
    def start(i: Int): Int

    /** The index following the last matched character, or -1 if nothing was matched. */
    def end: Int

    /** The index following the last matched character in group `i`,
     *  or -1 if nothing was matched for that group.
     */
    def end(i: Int): Int

    /** The matched string, or `null` if nothing was matched. */
    def matched: String =
      if (start >= 0) source.subSequence(start, end).toString
      else null

    /** The matched string in group `i`,
     *  or `null` if nothing was matched.
     */
    def group(i: Int): String =
      if (start(i) >= 0) source.subSequence(start(i), end(i)).toString
      else null

    /** All capturing groups, i.e., not including group(0). */
    def subgroups: List[String] = (1 to groupCount).toList map group

    /** The char sequence before first character of match,
     *  or `null` if nothing was matched.
     */
    def before: CharSequence =
      if (start >= 0) source.subSequence(0, start)
      else null

    /** The char sequence before first character of match in group `i`,
     *  or `null` if nothing was matched for that group.
     */
    def before(i: Int): CharSequence =
      if (start(i) >= 0) source.subSequence(0, start(i))
      else null

    /** Returns char sequence after last character of match,
     *  or `null` if nothing was matched.
     */
    def after: CharSequence =
      if (end >= 0) source.subSequence(end, source.length)
      else null

    /** The char sequence after last character of match in group `i`,
     *  or `null` if nothing was matched for that group.
     */
    def after(i: Int): CharSequence =
      if (end(i) >= 0) source.subSequence(end(i), source.length)
      else null

    private lazy val nameToIndex: Map[String, Int] = Map[String, Int]() ++ ("" :: groupNames.toList).zipWithIndex

    /** Returns the group with given name.
     *
     *  @param id The group name
     *  @return   The requested group
     *  @throws   NoSuchElementException if the requested group name is not defined
     */
    def group(id: String): String = nameToIndex.get(id) match {
      case None => throw new NoSuchElementException("group name "+id+" not defined")
      case Some(index) => group(index)
    }

    /** The matched string; equivalent to `matched.toString`. */
    override def toString = matched
  }

  /** Provides information about a successful match. */
  class Match(val source: CharSequence,
              private[matching] val matcher: Matcher,
              val groupNames: Seq[String]) extends MatchData {

    /** The index of the first matched character. */
    val start = matcher.start

    /** The index following the last matched character. */
    val end = matcher.end

    /** The number of subgroups. */
    def groupCount = matcher.groupCount

    private lazy val starts: Array[Int] =
      ((0 to groupCount) map matcher.start).toArray
    private lazy val ends: Array[Int] =
      ((0 to groupCount) map matcher.end).toArray

    /** The index of the first matched character in group `i`. */
    def start(i: Int) = starts(i)

    /** The index following the last matched character in group `i`. */
    def end(i: Int) = ends(i)

    /** The match itself with matcher-dependent lazy vals forced,
     *  so that match is valid even once matcher is advanced.
     */
    def force: this.type = { starts; ends; this }
  }

  /** An extractor object for Matches, yielding the matched string.
   *
   *  This can be used to help writing replacer functions when you
   *  are not interested in match data. For example:
   *
   *  {{{
   *  import scala.util.matching.Regex.Match
   *  """\w+""".r replaceAllIn ("A simple example.", _ match { case Match(s) => s.toUpperCase })
   *  }}}
   *
   */
  object Match {
    def unapply(m: Match): Some[String] = Some(m.matched)
  }

  /** An extractor object that yields the groups in the match. Using this extractor
   *  rather than the original `Regex` ensures that the match is not recomputed.
   *
   *  {{{
   *  import scala.util.matching.Regex.Groups
   *
   *  val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
   *  val text = "The doc spree happened on 2011-07-15."
   *  val day = date replaceAllIn(text, _ match { case Groups(_, month, day) => s"$month/$day" })
   *  }}}
   */
  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.
   *
   *  All methods inherited from [[scala.util.matching.Regex.MatchData]] will throw
   *  a [[java.lang.IllegalStateException]] until the matcher is initialized. The
   *  matcher can be initialized by calling `hasNext` or `next()` or causing these
   *  methods to be called, such as by invoking `toString` or iterating through
   *  the iterator's elements.
   *
   *  @see [[java.util.regex.Matcher]]
   */
  class MatchIterator(val source: CharSequence, val regex: Regex, val groupNames: Seq[String])
  extends AbstractIterator[String] with Iterator[String] with MatchData { self =>

    protected[Regex] val matcher = regex.pattern.matcher(source)
    private var nextSeen = false

    /** Is there another match? */
    def hasNext: Boolean = {
      if (!nextSeen) nextSeen = matcher.find()
      nextSeen
    }

    /** The next matched substring of `source`. */
    def next(): String = {
      if (!hasNext) throw new NoSuchElementException
      nextSeen = false
      matcher.group
    }

    override def toString = super[AbstractIterator].toString

    /** The index of the first matched character. */
    def start: Int = matcher.start

    /** The index of the first matched character in group `i`. */
    def start(i: Int): Int = matcher.start(i)

    /** The index of the last matched character. */
    def end: Int = matcher.end

    /** The index following the last matched character in group `i`. */
    def end(i: Int): Int = matcher.end(i)

    /** The number of subgroups. */
    def groupCount = matcher.groupCount

    /** Convert to an iterator that yields MatchData elements instead of Strings. */
    def matchData: Iterator[Match] = new AbstractIterator[Match] {
      def hasNext = self.hasNext
      def next = { self.next(); new Match(source, matcher, groupNames).force }
    }

    /** Convert to an iterator that yields MatchData elements instead of Strings and has replacement support. */
    private[matching] def replacementData = new AbstractIterator[Match] with Replacement {
      def matcher = self.matcher
      def hasNext = self.hasNext
      def next = { self.next(); new Match(source, matcher, groupNames).force }
    }
  }

  /**
   * A trait able to build a string with replacements assuming it has a matcher.
   * Meant to be mixed in with iterators.
   */
  private[matching] trait Replacement {
    protected def matcher: Matcher

    private val sb = new java.lang.StringBuffer

    def replaced = {
      val newsb = new java.lang.StringBuffer(sb)
      matcher.appendTail(newsb)
      newsb.toString
    }

    def replace(rs: String) = matcher.appendReplacement(sb, rs)
  }

  /** Quotes strings to be used literally in regex patterns.
   *
   *  All regex metacharacters in the input match themselves literally in the output.
   *
   *  @example {{{List("US$", "CAN$").map(Regex.quote).mkString("|").r}}}
   */
  def quote(text: String): String = Pattern quote text

  /** Quotes replacement strings to be used in replacement methods.
   *
   *  Replacement methods give special meaning to backslashes (`\`) and
   *  dollar signs (`$`) in replacement strings, so they are not treated
   *  as literals. This method escapes these characters so the resulting
   *  string can be used as a literal replacement representing the input
   *  string.
   *
   *  @param text The string one wishes to use as literal replacement.
   *  @return A string that can be used to replace matches with `text`.
   *  @example {{{"CURRENCY".r.replaceAllIn(input, Regex quoteReplacement "US$")}}}
   */
  def quoteReplacement(text: String): String = Matcher quoteReplacement text
}