-
Notifications
You must be signed in to change notification settings - Fork 0
Quantifiers
Mark Whitaker edited this page Aug 18, 2019
·
4 revisions
Quantifiers help you match a pattern more than once, many times, or not at all. For example:
- You want to find a string of consecutive digits, with at least one digit and no maximum.
- You want to find all the words of five letters or more within a string.
With RegexBuilder
you do this by passing a RegexQuantifier
object to an element or endGroup()
method. For example:
val regex = RegexBuilder()
.digit(RegexQuantifier.oneOrMore())
.buildRegex()
will give us a regex that matches one or more consecutive digits, and:
val regex = RegexBuilder()
.letter(RegexQuantifier.atLeast(5))
.buildRegex()
will give us a regex matching at least 5 consecutive letters.
Quantifiers can be passed into any element-matching method, or to endGroup()
in which case they apply to the whole group. They are specified using the static methods of the RegexQuantifier
class.
Quantifier | Matches | Raw regex equivalent |
---|---|---|
zeroOrMore() |
Any number of occurrences of the element or group, including none at all. | * |
oneOrMore() |
At least one occurrence of the element or group, but no maximum. | + |
noneOrOne() |
Either zero or one occurrence of the element or group. For example, .text("http").text("s", RegexQuantifier.noneOrOne()) will match both "http" and "https" . |
? |
Quantifier | Matches | Raw regex equivalent |
---|---|---|
exactly(times: Int) |
Exactly the specified number of occurrences of the element or group. |
{ x}
|
atLeast(minimum: Int) |
At least the specified minimum number of occurrences of the element or group. |
{ x,}
|
noMoreThan(maximum: Int) |
No more than the specified maximum number of occurrences of the element or group. |
{0, x}
|
between(minimum: Int, maximum: Int) |
At least the specified minimum, and no more than the specified maximum, number of occurrences of the element or group. |
{ x, y}
|
RegexToolbox: Now you can be a hero without knowing regular expressions.