Regular Expressions Part 2
(Pssst! All the code referenced in this post can be found in https://github.com/NerdcoreSteve/regular-expressions. Pass it on!)
This is part 2 in a series on regular expressions. Have a look at part 1 first if you haven't already, and have a look at part 3 when you're done.
Match One Or More
Here's a thing:
console.log(
'Read or the owl will eat you.'
.match(/[aeiou]+/g))
[ 'ea', 'o', 'e', 'o', 'i', 'ea', 'ou' ]
The +
at the end of the character class means we'll match any number of characters matching the character class. The +
operator works with any character as well as character classes:
console.log('111918829332911819238'.match(/1+/g))
[ '111', '1', '11', '1' ]
I can do the same trick with groups of characters by using parentheses:
console.log(
'I am a banana, you are a bananana, everybody is a bananananana'
.match(/b(an)+a/g))
[ 'banana', 'bananana', 'bananananana' ]
Ranges
Ok, check this out:
console.log(
'Why is 6 afraid of 7? Because 789!'
.match(/[0-9]+/g))
[ '6', '7', '789' ]
We can do ranges! And it doesn't have to just be 0 through 9:
console.log(
'We\'ll match 234, but not 190'
.match(/[2-5]+/g))
console.log(
'And we can match characters!'
.match(/[a-z]+/gi))
[ '234' ]
[ 'And', 'we', 'can', 'match', 'characters' ]
And we can include more than one range:
console.log(
'We can also match characters and numbers! 1, 2, 3, 45'
.match(/[a-z0-9]+/gi))
[ 'We',
'can',
'also',
'match',
'characters',
'and',
'numbers',
'1',
'2',
'3',
'45' ]
Escaping
What if I wanted to match characters like '['
or '+'
? Just put a slash in front of the character to escape it.
console.log('[1, 2, 1 + 2]'.match(/[\[\+]+/g))
[ '[', '+' ]
This goes for any reserved regex character, any time you want to match one, just put a \
in front of it. For example, if you want to match \
, then do \\
:
console.log('\\'.match(/\\/))
[ '\\', index: 0, input: '\\' ]
Note that, in order to put a \
in a string, we have to escape it just like we'd have to for a '
if we were using single quotes for a string like this: 'I\'ve got an escape plan!'
Move on to part 3!