Scala Standard Library 2.13.16 - scala.util.matching.Regex
Keywords: Scala Standard Library 2.13.16 scala.util.matching.Regex

Scala Standard Library2.13.16 < Back


# Packages

-  package root

  This is the documentation for the Scala standard library.

  This is the documentation for the Scala standard library.

  #### Package structure

  The scala package contains core types like `Int`, `Float`, `Array` or `Option` which are accessible in all Scala compilation units without explicit qualification or imports.

  Notable packages include:

  - `scala.collection` and its sub-packages contain Scala's collections framework
    - `scala.collection.immutable` - Immutable, sequential data-structures such as `Vector`, `List`, `Range`, `HashMap` or `HashSet`
    - `scala.collection.mutable` - Mutable, sequential data-structures such as `ArrayBuffer`, `StringBuilder`, `HashMap` or `HashSet`
    - `scala.collection.concurrent` - Mutable, concurrent data-structures such as `TrieMap`
  - `scala.concurrent` - Primitives for concurrent programming such as `Futures` and `Promises`
  - `scala.io` - Input and output operations
  - `scala.math` - Basic math functions and additional numeric types like `BigInt` and `BigDecimal`
  - `scala.sys` - Interaction with other processes and the operating system
  - `scala.util.matching` - Regular expressions

  Other packages exist. See the complete list on the right.

  Additional parts of the standard library are shipped as separate libraries. These include:

  - `scala.reflect` - Scala's reflection API (scala-reflect.jar)
  - `scala.xml` - XML parsing, manipulation, and serialization (scala-xml.jar)
  - `scala.collection.parallel` - Parallel collections (scala-parallel-collections.jar)
  - `scala.util.parsing` - Parser combinators (scala-parser-combinators.jar)
  - `scala.swing` - A convenient wrapper around Java's GUI framework called Swing (scala-swing.jar)

  #### Automatic imports

  Identifiers in the scala package and the `scala.Predef` object are always in scope by default.

  Some of these identifiers are type aliases provided as shortcuts to commonly used classes. For example, `List` is an alias for `scala.collection.immutable.List`.

  Other aliases refer to classes provided by the underlying platform. For example, on the JVM, `String` is an alias for `java.lang.String`.

  Definition Classes
    root
-  package scala

  Core Scala types.

  Core Scala types. They are always available without an explicit import.

  Definition Classes
    root
-  package util
  Definition Classes
    scala
-  package matching
  Definition Classes
    util
- Regex
- UnanchoredRegex

c

scala.util.matching

# Regex

###
Companion object Regex

#### class Regex extends Serializable

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.

##### Usage

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 = raw"(\d{4})-(\d{2})-(\d{2})".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"""`. The same result is achieved with certain interpolators, such as `raw"\d".r` or a custom interpolator `r"\d"` that also compiles the `Regex`.

##### Extraction

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."
    }

##### Find Matches

To find or replace matches of the pattern, use the various find and replace methods. For each method, there is a version for working with matched strings and another for working with `Match` objects.

For example, pattern matching with an unanchored `Regex`, as in the previous example, can also be accomplished using `findFirstMatchIn`. The `findFirst` methods return an `Option` which is non-empty if a match is found, 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)

To check whether input is matched by the regex:

    date.matches("2018-03-01")                     // true
    date.matches("Today is 2018-03-01")            // false
    date.unanchored.matches("Today is 2018-03-01") // true

To iterate over the matched strings, use `findAllIn`, which returns a special iterator that can be queried for the `MatchData` of the last match:

    val mi = date.findAllIn(dates)
    while (mi.hasNext) {
      val d = mi.next
      if (mi.group(1).toInt < 1960) println(s"$d: An oldie but goodie.")
    }

Although the `MatchIterator` returned by `findAllIn` is used like any `Iterator`, with alternating calls to `hasNext` and `next`, `hasNext` has the additional side effect of advancing the underlying matcher to the next unconsumed match. This effect is visible in the `MatchData` representing the "current match".

    val r = "(ab+c)".r
    val s = "xxxabcyyyabbczzz"
    r.findAllIn(s).start    // 3
    val mi = r.findAllIn(s)
    mi.hasNext              // true
    mi.start                // 3
    mi.next()               // "abc"
    mi.start                // 3
    mi.hasNext              // true
    mi.start                // 9
    mi.next()               // "abbc"

The example shows that methods on `MatchData` such as `start` will advance to the first match, if necessary. It also shows that `hasNext` will advance to the next unconsumed match, if `next` has already returned the current match.

The current `MatchData` can be captured using the `matchData` method. Alternatively, `findAllMatchIn` returns an `Iterator[Match]`, where there is no interaction between the iterator and `Match` objects it has already produced.

Note that `findAllIn` finds matches that don't overlap. (See findAllIn for more examples.)

    val num = raw"(\d+)".r
    val all = num.findAllIn("123").toList  // List("123"), not List("123", "23", "3")

##### Replace Text

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"
    })

Self Type
  Regex
Annotations
  @SerialVersionUID()
Source
  Regex.scala
See also

  java.util.regex.Pattern

Linear Supertypes
java.io.Serializable, AnyRef, Any
Known Subclasses
UnanchoredRegex
Type Hierarchy

Ordering

1. Alphabetic
2. By Inheritance

Inherited

1. Regex
2. Serializable
3. AnyRef
4. Any

Implicitly

1. by any2stringadd
2. by StringFormat
3. by Ensuring
4. by ArrowAssoc

1. Hide All
2. Show All

Visibility

1. Public
2. Protected

### Instance Constructors

1.  new Regex(regex: String, groupNames: String*)

   Compile a regular expression, supplied as a string, into a pattern that can be matched against inputs.

   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"

   Inline group names are preferred over group names supplied to the constructor when retrieving matched groups by name. Group names supplied to the constructor should be considered deprecated.

   This constructor does not support options as flags, which must be supplied as inline flags in the pattern string: `(?idmsuxU)`.

   regex

     The regular expression to compile.

   groupNames

     Names of capturing groups.

### Value Members

1.  final def !=(arg0: Any): Boolean

   Test two objects for inequality.

   Test two objects for inequality.

   returns

     `true` if !(this == that), false otherwise.

   Definition Classes
     AnyRef → Any
2.  final def ##: Int

   Equivalent to `x.hashCode` except for boxed numeric types and `null`.

   Equivalent to `x.hashCode` except for boxed numeric types and `null`. For numerics, it returns a hash value which is consistent with value equality: if two value type instances compare as true, then ## will produce the same hash value for each of them. For `null` returns a hashcode where `null.hashCode` throws a `NullPointerException`.

   returns

     a hash value consistent with ==

   Definition Classes
     AnyRef → Any
3.  def +(other: String): String
   Implicit
     This member is added by an implicit conversion from Regex toany2stringadd[Regex] performed by method any2stringadd in scala.Predef.
   Definition Classes
     any2stringadd
4.  def ->[B](y: B): (Regex, B)
   Implicit
     This member is added by an implicit conversion from Regex toArrowAssoc[Regex] performed by method ArrowAssoc in scala.Predef.
   Definition Classes
     ArrowAssoc
   Annotations
     @inline()
5.  final def ==(arg0: Any): Boolean

   The expression `x == that` is equivalent to `if (x eq null) that eq null else x.equals(that)`.

   The expression `x == that` is equivalent to `if (x eq null) that eq null else x.equals(that)`.

   returns

     `true` if the receiver object is equivalent to the argument; `false` otherwise.

   Definition Classes
     AnyRef → Any
6.  def anchored: Regex
7.  final def asInstanceOf[T0]: T0

   Forces the compiler to treat the receiver object as having type `T0`, even though doing so may violate type safety.

   Forces the compiler to treat the receiver object as having type `T0`, even though doing so may violate type safety.

   This method is useful when you believe you have type information the compiler doesn't, and it also isn't possible to check the type at runtime. In such situations, skipping type safety is the only option.

   It is platform dependent whether `asInstanceOf` has any effect at runtime. It might do a runtime type test on the erasure of `T0`, insert a conversion (such as boxing/unboxing), fill in a default value, or do nothing at all.

   In particular, `asInstanceOf` is not a type test. It does **not** mean:

       this match {
        case x: T0 => x
        case _     => throw ClassCastException("...")

   Use pattern matching or isInstanceOf for type testing instead.

   Situations where `asInstanceOf` is useful:

   - when flow analysis fails to deduce `T0` automatically
   - when down-casting a type parameter or an abstract type member (which cannot be checked at runtime due to type erasure) If there is any doubt and you are able to type test instead, you should do so.

   Be careful of using `asInstanceOf` when `T0` is a primitive type. When `T0` is primitive, `asInstanceOf` may insert a conversion instead of a type test. If your intent is to convert, use a `toT` method (`x.toChar`, `x.toByte`, etc.).

   returns

     the receiver object.

   Definition Classes
     Any
   Exceptions thrown

     `ClassCastException` if the receiver is not an instance of the erasure of `T0`, if that can be checked on this platform

8.  def clone(): AnyRef

   Create a copy of the receiver object.

   Create a copy of the receiver object.

   The default implementation of the `clone` method is platform dependent.

   returns

     a copy of the receiver object.

   Attributes
     protected[lang]
   Definition Classes
     AnyRef
   Annotations
     @throws(classOf[java.lang.CloneNotSupportedException]) @native()
   Note

     not specified by SLS as a member of AnyRef

9.  def ensuring(cond: (Regex) => Boolean, msg: => Any): Regex
   Implicit
     This member is added by an implicit conversion from Regex toEnsuring[Regex] performed by method Ensuring in scala.Predef.
   Definition Classes
     Ensuring
10.  def ensuring(cond: (Regex) => Boolean): Regex
    Implicit
      This member is added by an implicit conversion from Regex toEnsuring[Regex] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring
11.  def ensuring(cond: Boolean, msg: => Any): Regex
    Implicit
      This member is added by an implicit conversion from Regex toEnsuring[Regex] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring
12.  def ensuring(cond: Boolean): Regex
    Implicit
      This member is added by an implicit conversion from Regex toEnsuring[Regex] performed by method Ensuring in scala.Predef.
    Definition Classes
      Ensuring
13.  final def eq(arg0: AnyRef): Boolean

    Tests whether the argument (`that`) is a reference to the receiver object (`this`).

    Tests whether the argument (`that`) is a reference to the receiver object (`this`).

    The `eq` method implements an equivalence relation on non-null instances of `AnyRef`, and has three additional properties:

    - It is consistent: for any non-null instances `x` and `y` of type `AnyRef`, multiple invocations of `x.eq(y)` consistently returns `true` or consistently returns `false`.
    - For any non-null instance `x` of type `AnyRef`, `x.eq(null)` and `null.eq(x)` returns `false`.
    - `null.eq(null)` returns `true`.

    When overriding the `equals` or `hashCode` methods, it is important to ensure that their behavior is consistent with reference equality. Therefore, if two objects are references to each other (`o1 eq o2`), they should be equal to each other (`o1 == o2`) and they should hash to the same value (`o1.hashCode == o2.hashCode`).

    returns

      `true` if the argument is a reference to the receiver object; `false` otherwise.

    Definition Classes
      AnyRef
14.  def equals(arg0: AnyRef): Boolean

    The equality method for reference types.

    The equality method for reference types. Default implementation delegates to `eq`.

    See also `equals` in scala.Any.

    returns

      `true` if the receiver object is equivalent to the argument; `false` otherwise.

    Definition Classes
      AnyRef → Any
15.  def finalize(): Unit

    Called by the garbage collector on the receiver object when there are no more references to the object.

    Called by the garbage collector on the receiver object when there are no more references to the object.

    The details of when and if the `finalize` method is invoked, as well as the interaction between `finalize` and non-local returns and exceptions, are all platform dependent.

    Attributes
      protected[lang]
    Definition Classes
      AnyRef
    Annotations
      @throws(classOf[java.lang.Throwable])
    Note

      not specified by SLS as a member of AnyRef

16.  def findAllIn(source: CharSequence): MatchIterator

    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.

    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 after exhausting the iterator results in java.lang.IllegalStateException. See scala.util.matching.Regex.MatchIterator for details.

    source

      The text to match against.

    returns

      A scala.util.matching.Regex.MatchIterator of matched substrings.

    Example:

    1.     for (words <- """\w+""".r findAllIn "A simple example.") yield words

17.  def findAllMatchIn(source: CharSequence): Iterator[Match]

    Return all non-overlapping matches of this regexp in given character sequence as a scala.collection.Iterator of scala.util.matching.Regex.Match.

    Return all non-overlapping matches of this regexp in given character sequence as a scala.collection.Iterator of scala.util.matching.Regex.Match.

    source

      The text to match against.

    returns

      A scala.collection.Iterator of scala.util.matching.Regex.Match for all matches.

    Example:

    1.     for (words <- """\w+""".r findAllMatchIn "A simple example.") yield words.start

18.  def findFirstIn(source: CharSequence): Option[String]

    Return an optional first matching string of this `Regex` in the given character sequence, or None if there is no match.

    Return an optional first matching string of this `Regex` in the given character sequence, or None if there is no match.

    source

      The text to match against.

    returns

      An scala.Option of the first matching string in the text.

    Example:

    1.     """\w+""".r findFirstIn "A simple example." foreach println // prints "A"

19.  def findFirstMatchIn(source: CharSequence): Option[Match]

    Return an optional first match of this `Regex` in the given character sequence, or None if it does not exist.

    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.

    source

      The text to match against.

    returns

      A scala.Option of scala.util.matching.Regex.Match of the first matching string in the text.

    Example:

    1.     ("""[a-z]""".r findFirstMatchIn "A simple example.") map (_.start) // returns Some(2), the index of the first match in the text

20.  def findPrefixMatchOf(source: CharSequence): Option[Match]

    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.

    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.

    source

      The text to match against.

    returns

      A scala.Option of the scala.util.matching.Regex.Match of the matched string.

    Example:

    1.     """\w+""".r findPrefixMatchOf "A simple example." map (_.after) // returns Some(" simple example.")

21.  def findPrefixOf(source: CharSequence): Option[String]

    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.

    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.

    source

      The text to match against.

    returns

      A scala.Option of the matched prefix.

    Example:

    1.     """\p{Lower}""".r findPrefixOf "A simple example." // returns None, since the text does not begin with a lowercase letter

22.  final def getClass(): Class[_ <: AnyRef]

    Returns the runtime class representation of the object.

    Returns the runtime class representation of the object.

    returns

      a class object corresponding to the runtime type of the receiver.

    Definition Classes
      AnyRef → Any
    Annotations
      @native()
23.  def hashCode(): Int

    The hashCode method for reference types.

    The hashCode method for reference types. See hashCode in scala.Any.

    returns

      the hash code value for this object.

    Definition Classes
      AnyRef → Any
    Annotations
      @native()
24.  final def isInstanceOf[T0]: Boolean

    Test whether the dynamic type of the receiver object has the same erasure as `T0`.

    Test whether the dynamic type of the receiver object has the same erasure as `T0`.

    Depending on what `T0` is, the test is done in one of the below ways:

    - `T0` is a non-parameterized class type, e.g. `BigDecimal`: this method returns `true` if the value of the receiver object is a `BigDecimal` or a subtype of `BigDecimal`.
    - `T0` is a parameterized class type, e.g. `List[Int]`: this method returns `true` if the value of the receiver object is some `List[X]` for any `X`. For example, `List(1, 2, 3).isInstanceOf[List[String]]` will return true.
    - `T0` is some singleton type `x.type` or literal `x`: this method returns `this.eq(x)`. For example, `x.isInstanceOf[1]` is equivalent to `x.eq(1)`
    - `T0` is an intersection `X with Y` or `X & Y: this method is equivalent to` x.isInstanceOf[X] && x.isInstanceOf[Y]``
    - `T0` is a union `X | Y`: this method is equivalent to `x.isInstanceOf[X] || x.isInstanceOf[Y]`
    - `T0` is a type parameter or an abstract type member: this method is equivalent to `isInstanceOf[U]` where `U` is `T0`'s upper bound, `Any` if `T0` is unbounded. For example, `x.isInstanceOf[A]` where `A` is an unbounded type parameter will return true for any value of `x`.

    This is exactly equivalent to the type pattern `_: T0`

    returns

      `true` if the receiver object is an instance of erasure of type `T0`; `false` otherwise.

    Definition Classes
      Any
    Note

      due to the unexpectedness of `List(1, 2, 3).isInstanceOf[List[String]]` returning true and `x.isInstanceOf[A]` where `A` is a type parameter or abstract member returning true, these forms issue a warning.

25.  def matches(source: CharSequence): Boolean

    Returns whether this `Regex` matches the given character sequence.

    Returns whether this `Regex` matches the given character sequence.

    Like the extractor, this method takes anchoring into account.

    source

      The text to match against

    returns

      true if and only if `source` matches this `Regex`.

    Example:

    1.     """\d+""".r matches "123" // returns true

    See also

      Regex#unanchored

26.  final def ne(arg0: AnyRef): Boolean

    Equivalent to `!(this eq that)`.

    Equivalent to `!(this eq that)`.

    returns

      `true` if the argument is not a reference to the receiver object; `false` otherwise.

    Definition Classes
      AnyRef
27.  final def notify(): Unit

    Wakes up a single thread that is waiting on the receiver object's monitor.

    Wakes up a single thread that is waiting on the receiver object's monitor.

    Definition Classes
      AnyRef
    Annotations
      @native()
    Note

      not specified by SLS as a member of AnyRef

28.  final def notifyAll(): Unit

    Wakes up all threads that are waiting on the receiver object's monitor.

    Wakes up all threads that are waiting on the receiver object's monitor.

    Definition Classes
      AnyRef
    Annotations
      @native()
    Note

      not specified by SLS as a member of AnyRef

29.  val pattern: Pattern
30.  def regex: String
31.  def replaceAllIn(target: CharSequence, replacer: (Match) => String): String

    Replaces all matches using a replacer function.

    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"}")

    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.

    target

      The string to match.

    replacer

      The function which maps a match to another string.

    returns

      The target string after replacements.

32.  def replaceAllIn(target: CharSequence, replacement: String): String

    Replaces all matches by a string.

    Replaces all matches by a string.

    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.

    target

      The string to match

    replacement

      The string that will replace each match

    returns

      The resulting string

    Example:

    1.     """\d+""".r replaceAllIn ("July 15", "<NUMBER>") // returns "July <NUMBER>"

33.  def replaceFirstIn(target: CharSequence, replacement: String): String

    Replaces the first match by a string.

    Replaces the first match by a string.

    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.

    target

      The string to match

    replacement

      The string that will replace the match

    returns

      The resulting string

34.  def replaceSomeIn(target: CharSequence, replacer: (Match) => Option[String]): String

    Replaces some of the matches using a replacer function that returns an scala.Option.

    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)

    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.

    target

      The string to match.

    replacer

      The function which optionally maps a match to another string.

    returns

      The target string after replacements.

35.  def runMatcher(m: Matcher): Boolean
    Attributes
      protected
36.  def split(toSplit: CharSequence): Array[String]

    Splits the provided character sequence around matches of this regexp.

    Splits the provided character sequence around matches of this regexp.

    toSplit

      The character sequence to split

    returns

      The array of strings computed by splitting the input around matches of this regexp

37.  final def synchronized[T0](arg0: => T0): T0

    Executes the code in `body` with an exclusive lock on `this`.

    Executes the code in `body` with an exclusive lock on `this`.

    returns

      the result of `body`

    Definition Classes
      AnyRef
38.  def toString(): String

    The string defining the regular expression

    The string defining the regular expression

    returns

      a String representation of the object.

    Definition Classes
      Regex → AnyRef → Any
39.  def unanchored: UnanchoredRegex

    Create a new Regex with the same pattern, but no requirement that the entire String matches in extractor patterns and Regex#matches.

    Create a new Regex with the same pattern, but no requirement that the entire String matches in extractor patterns and Regex#matches.

    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"
        }

    returns

      The new unanchored regex

40.  def unapplySeq(m: Match): Option[List[String]]

    Tries to match on a scala.util.matching.Regex.Match.

    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.

41.  def unapplySeq(c: Char): Option[List[Char]]

    Tries to match the String representation of a scala.Char.

    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

    c

      The Char to match

    returns

      The match

42.  def unapplySeq(s: CharSequence): Option[List[String]]

    Tries to match a java.lang.CharSequence.

    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 _        => ""
        }

    s

      The string to match

    returns

      The matches

43.  final def wait(): Unit

    See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--.

    See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--.

    Definition Classes
      AnyRef
    Annotations
      @throws(classOf[java.lang.InterruptedException])
    Note

      not specified by SLS as a member of AnyRef

44.  final def wait(arg0: Long, arg1: Int): Unit

    See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait-long-int-

    See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait-long-int-

    Definition Classes
      AnyRef
    Annotations
      @throws(classOf[java.lang.InterruptedException])
    Note

      not specified by SLS as a member of AnyRef

45.  final def wait(arg0: Long): Unit

    See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait-long-.

    See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait-long-.

    Definition Classes
      AnyRef
    Annotations
      @throws(classOf[java.lang.InterruptedException]) @native()
    Note

      not specified by SLS as a member of AnyRef

### Deprecated Value Members

1.  def formatted(fmtstr: String): String

   Returns string formatted according to given `format` string.

   Returns string formatted according to given `format` string. Format strings are as for `String.format` (@see java.lang.String.format).

   Implicit
     This member is added by an implicit conversion from Regex toStringFormat[Regex] performed by method StringFormat in scala.Predef.
   Definition Classes
     StringFormat
   Annotations
     @deprecated @inline()
   Deprecated

     (Since version 2.12.16) Use `formatString.format(value)` instead of `value.formatted(formatString)`, or use the `f""` string interpolator. In Java 15 and later, `formatted` resolves to the new method in String which has reversed parameters.

2.  def →[B](y: B): (Regex, B)
   Implicit
     This member is added by an implicit conversion from Regex toArrowAssoc[Regex] performed by method ArrowAssoc in scala.Predef.
   Definition Classes
     ArrowAssoc
   Annotations
     @deprecated
   Deprecated

     (Since version 2.13.0) Use `->` instead. If you still wish to display it as one character, consider using a font with programming ligatures such as Fira Code.

### Inherited from java.io.Serializable

### Inherited from AnyRef

### Inherited from Any

### Inherited by implicit conversion any2stringadd fromRegex to any2stringadd[Regex]

### Inherited by implicit conversion StringFormat fromRegex to StringFormat[Regex]

### Inherited by implicit conversion Ensuring fromRegex to Ensuring[Regex]

### Inherited by implicit conversion ArrowAssoc fromRegex to ArrowAssoc[Regex]

### Ungrouped