20. Metacharacters - Quantifiers: The Question Mark
- The question mark provides a way of saying that the modified character is
optional. That is, it can occur either once or zero times.
- For example, if we wrote the regular expression:
1234 ?5678
then the regular expression would match a "1", then a "2", then a "3", then
a "4", followed by zero or one spaces, followed by a "5", then a "6", etc.
- So, the regex would match when tested on "1234 5678" and "12345678".
- The question mark would also be useful if we wanted to search for
something like:
colou?r
- See how it would match either "color" or "colour"?
- Of course, using something like:
gre?a?y
is not the same as our regexes from before to match either "grey" or "gray",
because while both "gray" and "grey" will match, so will "gry" and "greay".
Not the same thing!
- Notice that "gry" would match - this is important. Because the question
mark is successful when the character it quantifies occurs zero or one
times, you can be assured that at the very least, the zero times will
succeed - so the question mark quantifier will always be successful!
|