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.

Learn how data is stored

Data Structures and Algorithms Made Easy

Learn how data is stored Try Data Structures

A handy guide of sorts for any computer science professional, Data Structures And Algorithms Made Easy in Java: Data Structure And Algorithmic Puzzles is a solution bank for various complex problems related to data structures and algorithms. It can be used as a reference manual by those readers in the computer science industry.

$ Check price
39.9939.99Amazon 4.5 logo(339+ reviews)

More Data Structures resources

Take your Linux skills to the next level!

Linux for Beginners

Take your Linux skills to the next level! Try Linux & UNIX

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

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

More Linux & UNIX resources

Ad