Regular Expressions: Maybe
Welcome to the Maybe lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
The
?operator matches a character zero or one times, but not more than one.>
/^a?$/.test('a');Result:
true
>
/^a?$/.test('');Result:
true
>
/^a?$/.test('b');Result:
false
>
/^a?$/.test('aa');Result:
false
The
?operator affects whatever is immediately before it. For example, inab?, the?operators only affects "b", not "a". We say that it binds tightly.>
/^ab?$/.test('a');Result:
true
>
/^ab?$/.test('b');Result:
false
>
/^ab?$/.test('ab');Result:
true
Often, part of a string is optional. For example, US telephone numbers sometimes have area codes. But for local calls, no area code is necessary. For optional strings like this, we can use the
?operator.>
/^555-?555-5555$/.test('555-555-5555');Result:
true
Unfortunately, this regex isn't quite right. The
?only applies to the "-" character before it, so only that character is optional. All of the other characters are required.>
/^555-?555-5555$/.test('555555-5555');Result:
true
To make
?include more characters, we can group them using parentheses. Then we apply the?to the whole group.>
/^(555-)?555-5555$/.test('555-555-5555');Result:
true
>
/^(555-)?555-5555$/.test('555-5555');Result:
true
>
/^(555-)?555-5555$/.test('555555-5555');Result:
false