-
Notifications
You must be signed in to change notification settings - Fork 2
Quantifiers
Mark Whitaker edited this page Nov 18, 2019
·
3 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:
var regex = new RegexBuilder()
.Digit(RegexQuantifier.OneOrMore)
.BuildRegex();
will give us a regex that matches one or more consecutive digits, and:
var regex = new 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 public properties and 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. | + |
ZeroOrOne |
Either zero or one occurrence of the element or group. For example, .Text("http").Text("s", RegexQuantifier.ZeroOrOne) will match both "http" and "https" . |
? |
Quantifier | Matches | Raw regex equivalent |
---|---|---|
Exactly(int times) |
Exactly the specified number of occurrences of the element or group. | {x} |
AtLeast(int minimum) |
At least the specified minimum number of occurrences of the element or group. | {x,} |
NoMoreThan(int maximum) |
No more than the specified maximum number of occurrences of the element or group. | {0,x} |
Between(int minimum, int maximum) |
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.