Skip to content

Quantifiers

Mark Whitaker edited this page Apr 13, 2023 · 6 revisions

Contents

Overview

Quantifiers help you match a pattern more than once, many times, or not at all. For example:

  1. You want to find a string of consecutive digits, with at least one digit and no maximum.
  2. 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:

Pattern regex = new RegexBuilder()
    .digit(RegexQuantifier.oneOrMore())
    .buildRegex();

will give us a regex that matches one or more consecutive digits, and:

Pattern 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 methods of the RegexQuantifier class.

Methods

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". ?
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}

Download from JitPack

Clone this wiki locally