Lesson 10: Exploring the Question Mark (?) Quantifier
Regular expressions are teeming with quantifiers, each holding its own unique functionality. One such quantifier is the question mark ?
. Unlike some other quantifiers which focus on repetition, the question mark quantifier is all about optionality. In this lesson, we'll shed light on this intriguing aspect of regex.
Defining the Question Mark (?) Quantifier
The ?
quantifier denotes zero or one occurrence of the preceding element. Essentially, it makes the character or group before it optional.
Basic Usage
Suppose you're capturing both American and British spellings. For instance, the word "color" in American English and "colour" in British English:
colou?r
This pattern would match both color
and colour
as the u
is made optional by the question mark.
Pairing with Other Elements
The question mark quantifier can be effectively paired with other elements of regex. For example, the pattern https?://
will match both http://
and https://
, accommodating websites with and without SSL encryption.
Common Usage Scenarios
The question mark quantifier becomes handy in cases such as:
- Matching alternative spellings or forms.
- Checking optional prefixes or suffixes in words.
- Validating user inputs where certain fields are optional.
Potential Pitfalls
It's crucial to remember that the question mark quantifier should be used judiciously. If placed without a clear intent, it can make your pattern too permissive, leading to undesired matches. Testing your regex pattern against varied inputs is always recommended.
Exercise 10: Getting Familiar with the Question Mark (?) Quantifier
Time to apply what we've learned about the question mark quantifier in practical scenarios. The objective here is to use the question mark quantifier to validate URL:s that are either using the http
or https
protocols, without matching incomplete URL:s or localhost
.