If you want to see real examples of the *
quantifier being used. Just look around Stack Overflow! Find someone who answers a lot of regex questions, like Wiktor Stribiżew and search for the use of *
in his answers. Here's an answer of mine that uses *
.
A use case of *
that is very common is to match spaces which are optional. Oftentimes when you ask for user input, you'd want to be as permissive as possible (users can add as many spaces as they like, or none at all) instead of following a very strict syntax.
For example, phone numbers. Where I live, phone numbers are 8 digits and they are grouped in groups of 4. e.g.
1234 5678
To be as permissive as possible, a regex like this can be used:
^\s*(\d{4})\s*(\d{4})\s*$
See the use of *
? It allows any number (including 0) of trailing, leading spaces, and spaces in the middle. Even if the user accidentally typed two spaces in the middle, the program can still understand them.
The regex can match all these
1234 5678
12345678
1234 5678
1234 5678
Or I can be even more permissive and allow spaces everywhere:
^(?:\s*\d\s*){8}$
Anyway, things you think are not useful will come in handy one day, when you need them. When I was learning how to code, I used to think "There's no way this language feature is useful", but when I was actually writing code to solve problems, very often I started using those features that I thought "were not useful". You just haven't encountered problems where it is suitable to use *
.