Number of occurences using {}



The literals +,?,* or the curly brackets {}, used to match the number of occurrences are also called quantifiers. Quantifiers match the preceding subpattern a certain number of times.

You will also notice that *, + and ? can always be expressed in terms of the curly pattern quantifier.

* is equivalent to {0,}. It matches zero or more times.

+ is equivalent to for {1,}. It matches one or more times.

? is equivalent to {0,1}. It matches zero or one time.

Ideally it should be possible to do away with *, + , ? and use only the curly brackets. But regular expressions are notorious for brevity. If you can sacrifice the brevity you may like to opt for the curly bracket style. However, to understand other’s code you will still need an understanding of the *, + and ? quantifiers.

1.10 More complex Patterns with combination of metacharacters



So far we have created patterns to search using single special characters. We call these special characters meta characters. We can use a combination of these meta characters to create more powerful search patterns.

Let us see some examples of the patterns created with the combinations of these meta characters.

Pattern ^micha?el$ maches michael and michel but not michelle
Pattern ^to{1,2}l matches strings tool, tol, but not toool or intool.
Pattern smo+ch$ matches smooch and smoch but not smooching
Pattern ^te*th matches teeth but not bad teeth
Pattern lo?o$ matches loo, lo but not lol
Pattern lu+lu$ matches lulu and luulu but not lul