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.
A Regex that finds the first match when used in a pattern match.
A Regex that finds the first match when used in a pattern match.
This object defines inner classes that describe regex matches and helper objects.
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 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"""
.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.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 usingfindFirstMatchIn
, except that the findFirst methods return anOption
, orNone
for no match:To find all matches:
But
findAllIn
returns a special iterator of strings that can be queried for theMatchData
of the last match:Note that
findAllIn
finds matches that don't overlap. (See findAllIn for more examples.)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:1.1, 29/01/2008
java.util.regex.Pattern