Regular Expressions: Literals
Welcome to the Literals lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Regular expressions (regexes) are patterns that describe strings. We might write a regex for filenames ending in ".jpg". Or we might write one that recognizes phone numbers. We'll use JavaScript's regexes, but it's OK if you don't know JavaScript.
We can ask whether a regex matches a given string:
/a/.test('cat'). The regex/a/means "any string containing an a". We asked about'cat', which contains an "a", so we'll gettrueback.>
/a/.test('a');Result:
true
>
/a/.test('b');Result:
false
>
/a/.test('xax');Result:
true
Regexes are case-sensitive, so "a" and "A" are different characters.
>
/A/.test('a');Result:
false
>
/A/.test('A');Result:
true
Multi-character regexes test that the characters appear together. They have to be adjacent, with no other characters between them.
>
/cat/.test('cart');Result:
false
>
/cat/.test('cat');Result:
true
>
/cat/.test('the cat there');Result:
true
Spaces are treated as normal characters. If they're in the regex, they'll have to be in the matched string too. Likewise for
_,-, and some other punctuation. (But some punctuation has special meaning, which we'll see soon.)>
/a cat/.test('that is a cat');Result:
true
>
/_/.test('happy-cat');Result:
false
>
/_/.test('happy_cat');Result:
true