Regular Expressions: Parens
Welcome to the Parens lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
This regex seems to match strings of exactly one "a" or exactly one "b". But that's not all it matches!
>
/^a|b$/.test('a');Result:
true
>
/^a|b$/.test('b');Result:
true
>
/^a|b$/.test('xa');Result:
false
>
/^a|b$/.test('ax');Result:
true
Why did
/^a|b$/accept the string "ax"? It makes more sense if we parenthesize the regex. (Parentheses group operators together, like in other programming languages.)>
/(^a)|(b$)/.test('xa');Result:
false
>
/(^a)|(b$)/.test('ax');Result:
true
When we say
/^a|b$/, it means the same as/(^a)|(b$)/. We might prefer it to mean/^(a|b)$/, but it is the way it is. Fortunately, adding those parentheses ourselves will help.>
/^(a|b)$/.test('a');Result:
true
>
/^(a|b)$/.test('xa');Result:
false
>
/^(a|b)$/.test('ax');Result:
false
>
/^(a|b)$/.test('xb');Result:
false
>
/^(a|b)$/.test('b');Result:
true
>
/^(a|b)$/.test('bx');Result:
false
Imagine that we have a system that can read images. But it can only read JPGs, PNGs, and PDFs; anything else makes it crash. We want a regex that will accept images based on their filename.
>
/^(jpg|png|pdf)$/.test('jpg');Result:
true
>
/^(jpg|png|pdf)$/.test('jpeg');Result:
false
>
/^(jpg|png|pdf)$/.test('png');Result:
true
>
/^(jpg|png|pdf)$/.test('pdf');Result:
true
As in math or normal programming, parentheses can "factor out" common elements.
>
/^(jpg|p(ng|df))$/.test('jpg');Result:
true
>
/^(jpg|p(ng|df))$/.test('jpeg');Result:
false
>
/^(jpg|p(ng|df))$/.test('pdf');Result:
true
>
/^(jpg|p(ng|df))$/.test('png');Result:
true
>
/^(jpg|p(ng|df))$/.test('p');Result:
false
We can use operators on parenthesized groups. In this example, the
+matches strings of one or more characters. The(a|b)requires each of those characters to be an "a" or a "b".>
/^(a|b)+$/.test('aaaaab');Result:
true
>
/^(a|b)+$/.test('bababa');Result:
true
>
/^(a|b)+$/.test('');Result:
false
Either side of a
|can be empty. This regex means "exactly the letter a, or the empty string".>
/^(a|)$/.test('a');Result:
true
>
/^(a|)$/.test('');Result:
true
>
/^(a|)$/.test('aa');Result:
false