Basic Quantifiers in Regular Expressions
1. The Question Mark (?)
The question mark ?
is a quantifier that matches zero or one occurrence of the preceding element. It is used to indicate that the preceding element is optional.
Example:
Pattern: colou?r
Matches: "color" and "colour"
Explanation: The u?
part means the letter "u" can appear zero or one time, making both "color" and "colour" valid matches.
2. The Asterisk (*)
The asterisk *
is a quantifier that matches zero or more occurrences of the preceding element. It is used to indicate that the preceding element can appear any number of times, including none.
Example:
Pattern: go*d
Matches: "gd", "god", "good", "gooood"
Explanation: The o*
part means the letter "o" can appear zero or more times, making all the above strings valid matches.
3. The Plus Sign (+)
The plus sign +
is a quantifier that matches one or more occurrences of the preceding element. It is used to indicate that the preceding element must appear at least once.
Example:
Pattern: go+d
Matches: "god", "good", "gooood"
Explanation: The o+
part means the letter "o" must appear at least once, making "gd" not a valid match.