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
Regexrepresents a compiled regular expression pattern. Since compilation is expensive, frequently usedRegexes should be constructed once, outside of loops and perhaps in a companion object.The canonical way to create a
Regexis 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
Regexis matched, use it as an extractor in a pattern match:To check only whether the
Regexmatches, ignoring any groups, use a sequence wildcard:That works because a
Regexextractor produces a sequence of strings. Extracting only the year from a date could also be expressed with a sequence wildcard:In a pattern match,
Regexnormally matches the entire input. However, an unanchoredRegexfinds 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
Matchobjects.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, orNonefor no match:To find all matches:
But
findAllInreturns a special iterator of strings that can be queried for theMatchDataof the last match:Note that
findAllInfinds 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
Matchagainst theRegexthat created it does not reapply theRegex. In the expression forreformatted, eachdatematch is computed once. But it is possible to apply aRegexto aMatchresulting from a different pattern:1.1, 29/01/2008
java.util.regex.Pattern