Regular Expressions Part 2

(Pssst! All the code referenced in this post can be found in 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:

    'Read or the owl will eat you.'
[ '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:

[ '111', '1', '11', '1' ]

I can do the same trick with groups of characters by using parentheses:

    'I am a banana, you are a bananana, everybody is a bananananana'
[ 'banana', 'bananana', 'bananananana' ]


Ok, check this out:

    'Why is 6 afraid of 7? Because 789!'
[ '6', '7', '789' ]

We can do ranges! And it doesn't have to just be 0 through 9:

    'We\'ll match 234, but not 190'
    'And we can match characters!'
[ '234' ]
[ 'And', 'we', 'can', 'match', 'characters' ]

And we can include more than one range:

    'We can also match characters and numbers! 1, 2, 3, 45'
[ 'We',
  '45' ]


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 \\:

[ '\\', 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!'

Ok, that's it for now. Move on to part 3!

Looking for a software developer?