Hone

Lessons · Regex · *: none or more

Zero or more

* means zero or more of the token before it, so a* matches the empty string in any text. It is + with 'nothing at all' allowed.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Optional runs are everywhere: spaces that may or may not be there, a sign before a number, a list that may be empty. * says 'if present, all of it'.

How to think about it

Use * for things that may be absent, + for things that must be present. If a pattern matches empty strings all over your text, a * is probably doing it.

Worked example

pattern: colou*r
Zero or more u: color, colour, colouur.
text: color colour
Both match.
pattern: \s*=\s*
Any spacing around an equals sign, including none.
text: a=1 and b = 2
Matches = and ' = ' alike.

Your turn

Digits, possibly none, after an optional minus.

-?\d

The trap

a* matches the empty string, so findall on a text with no a returns a list of empty matches, one per position. When you mean 'some', write +.

Practise *: none or more on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.