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"
Group names supplied to the constructor are preferred to inline group names when retrieving matched groups by name. Not all platforms support inline names.
This constructor does not support options as flags, which must be supplied as inline flags in the pattern string: (?idmsux-idmsux)
.
The regular expression to compile.
Names of capturing groups.
Test two objects for inequality.
true
if !(this == that), false otherwise.
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
.
a hash value consistent with ==
The expression x == that
is equivalent to if (x eq null) that eq null else x.equals(that)
.
true
if the receiver object is equivalent to the argument; false
otherwise.
Cast the receiver object to be of type T0
.
Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression 1.asInstanceOf[String]
will throw a ClassCastException
at runtime, while the expression List(1).asInstanceOf[List[String]]
will not. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the requested type.
the receiver object.
ClassCastException
if the receiver object is not an instance of the erasure of type T0
.
Create a copy of the receiver object.
The default implementation of the clone
method is platform dependent.
a copy of the receiver object.
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:
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
).
true
if the argument is a reference to the receiver object; false
otherwise.
The equality method for reference types. Default implementation delegates to eq
.
See also equals
in scala.Any.
true
if the receiver object is equivalent to the argument; false
otherwise.
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.
not specified by SLS as a member of AnyRef
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.
The text to match against.
A scala.util.matching.Regex.MatchIterator of matched substrings.
for (words <- """\w+""".r findAllIn "A simple example.") yield words
Return all non-overlapping matches of this regexp in given character sequence as a scala.collection.Iterator of scala.util.matching.Regex.Match.
The text to match against.
A scala.collection.Iterator of scala.util.matching.Regex.Match for all matches.
for (words <- """\w+""".r findAllMatchIn "A simple example.") yield words.start
Return an optional first matching string of this Regex
in the given character sequence, or None if there is no match.
The text to match against.
An scala.Option of the first matching string in the text.
"""\w+""".r findFirstIn "A simple example." foreach println // prints "A"
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.
The text to match against.
A scala.Option of scala.util.matching.Regex.Match of the first matching string in the text.
("""[a-z]""".r findFirstMatchIn "A simple example.") map (_.start) // returns Some(2), the index of the first match in the text
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.
The text to match against.
A scala.Option of the scala.util.matching.Regex.Match of the matched string.
"""\w+""".r findPrefixMatchOf "A simple example." map (_.after) // returns Some(" simple example.")
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.
The text to match against.
A scala.Option of the matched prefix.
"""\p{Lower}""".r findPrefixOf "A simple example." // returns None, since the text does not begin with a lowercase letter
Returns string formatted according to given format
string. Format strings are as for String.format
(@see java.lang.String.format).
Returns the runtime class representation of the object.
a class object corresponding to the runtime type of the receiver.
The hashCode method for reference types. See hashCode in scala.Any.
the hash code value for this object.
Test whether the dynamic type of the receiver object is T0
.
Note that the result of the test is modulo Scala's erasure semantics. Therefore the expression 1.isInstanceOf[String]
will return false
, while the expression List(1).isInstanceOf[List[String]]
will return true
. In the latter example, because the type argument is erased as part of compilation it is not possible to check whether the contents of the list are of the specified type.
true
if the receiver object is an instance of erasure of type T0
; false
otherwise.
Equivalent to !(this eq that)
.
true
if the argument is not a reference to the receiver object; false
otherwise.
Wakes up a single thread that is waiting on the receiver object's monitor.
not specified by SLS as a member of AnyRef
Wakes up all threads that are waiting on the receiver object's monitor.
not specified by SLS as a member of AnyRef
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.
The string to match.
The function which maps a match to another string.
The target string after replacements.
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.
The string to match
The string that will replace each match
The resulting string
"""\d+""".r replaceAllIn ("July 15", "<NUMBER>") // returns "July <NUMBER>"
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.
The string to match
The string that will replace the match
The resulting string
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.
The string to match.
The function which optionally maps a match to another string.
The target string after replacements.
Splits the provided character sequence around matches of this regexp.
The character sequence to split
The array of strings computed by splitting the input around matches of this regexp
The string defining the regular expression
a String representation of the object.
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" }
The new unanchored regex
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.
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
The Char to match
The match
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 _ => "" }
The string to match
The matches
© 2002-2019 EPFL, with contributions from Lightbend.
Licensed under the Apache License, Version 2.0.
https://www.scala-lang.org/api/2.12.9/scala/util/matching/Regex.html
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 usedRegex
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 methodr
, provided implicitly for strings: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 asraw"\d".r
or a custom interpolatorr"\d"
that also compiles theRegex
.Extraction
To extract the capturing groups when a
Regex
is matched, use it as an extractor in a pattern match:To check only whether the
Regex
matches, ignoring any groups, use a sequence wildcard: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:In a pattern match,
Regex
normally matches the entire input. However, an unanchoredRegex
finds the pattern anywhere in the input.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 usingfindFirstMatchIn
. ThefindFirst
methods return anOption
which is non-empty if a match is found, orNone
for no match:To find all matches:
To iterate over the matched strings, use
findAllIn
, which returns a special iterator that can be queried for theMatchData
of the last match:Although the
MatchIterator
returned byfindAllIn
is used like anyIterator
, with alternating calls tohasNext
andnext
,hasNext
has the additional side effect of advancing the underlying matcher to the next unconsumed match. This effect is visible in theMatchData
representing the "current match".The example shows that methods on
MatchData
such asstart
will advance to the first match, if necessary. It also shows thathasNext
will advance to the next unconsumed match, ifnext
has already returned the current match.The current
MatchData
can be captured using thematchData
method. Alternatively,findAllMatchIn
returns anIterator[Match]
, where there is no interaction between the iterator andMatch
objects it has already produced.Note that
findAllIn
finds matches that don't overlap. (See findAllIn for more examples.)Replace Text
Text replacement can be performed unconditionally or as a function of the current match:
Pattern matching the
Match
against theRegex
that created it does not reapply theRegex
. In the expression forreformatted
, eachdate
match is computed once. But it is possible to apply aRegex
to aMatch
resulting from a different pattern:java.util.regex.Pattern