03. Repetitions and Optionals

Reiterating a single regex expression

If we want to reiterate a single regex expression, we can do so with braces ({}). Within the braces we can specify up to two numbers, separated by a comma.

{n}
Match preceding element (if it occurs) exactly n times.
{n,m}
at least n times, but no more than m times.
{n,}
n or more times.
{,m}
no more than m times.

Here are some concrete examples:

.{4,}
Match any character 4 or more times.
\d{5,10}
Match any digit between 5 and 10 times.
Matching zero or many elements

To match an element zero or many times, use the Kleene star, which is an asterisk (*) placed after a specific character.

Match at least one element

To match a previous element at least once, use the Kleene plus (+). This is a tighter regulation than the Kleene star, as it ensures there is at least one of the preceding character.

Optional

To match an element zero or just one time, use the question mark (?). To match an actual question mark, escape it. (\?).

\d*
Match zero or many digits.
[a-z]+
Match one or many lowercase alphabet letters.
[abc]?
Match the characters a, b or c zero or just once.

Conditionals

You can use conditionals to specify either-or relations. Use the logical or (|) between two options.

(cats|dogs)
Selects either cats or dogs.

Build modern and responsive webpages

Responsive Typography

Build modern and responsive webpages Try Front-end

Responsive web design helps your site maintain its design integrity on a variety of screen sizes, but how does it affect your typography? With this practical book, graphic designers, web designers, and front-end developers alike will learn the nuts and bolts of how to get the best appearance from type without sacrificing performance on any device.

$ Check price
24.9924.99Amazon 4.5 logo(3+ reviews)

More Front-end resources

Ace your Technical Interview

Algorithms

Ace your Technical Interview Try Algorithms

This fourth edition of Algorithms is the leading textbook on algorithms today and is widely used in universities worldwide. This book surveys the most important computer algorithms currently in use and provides a full treatment of data structures and algorithms for sorting, searching, graph processing, and string processing.

$ Check price
89.9989.99Amazon 4.5 logo(148+ reviews)

More Algorithms resources

Ad