Regular Expressions Part 3

(Pssst! All the code referenced in this post can be found in https://github.com/NerdcoreSteve/regular-expressions. Pass it on!)

This is part 3 in a series on regular expressions. Have a look at part 1 and part 2 if you haven't already.

Match Beginning or Ending

The ^ character matches the beginning of a string, the $ character matches the end of a string. If you have a regex that begins with a ^ and ends with a $ then the entire string has to match your pattern or not at all.

Some Examples

JavaScript:

console.log(  
    'Potatoes are my friends, potatoes are my family.'
        .match(/^potatoes/gi))

output:

[ 'Potatoes' ]

JavaScript:

console.log(  
    'Family Ties is a good show, but I prefer All In the Family.'
        .match(/family.$/gi))

output:

[ 'Family.' ]

JavaScript:

console.log(  
    'The Magic School Bus was a great show, but they really should have asked that kid\'s parents before    driving through his digestive system'
        .match(/bu/gi))

output

[ 'Bu', 'bu' ]

JavaScript:

console.log(  
    'The Magic School Bus was a great show, but they really should have asked that kid\'s parents before    driving through his digestive system'
        .match(/^bu$/gi))

output:

null  

Short-Hand Patterns

Regex-land has some really useful short-hand patterns:

console.log(  
    'A baker\'s dozen is 13. Why is that?'
        .match(/\d+/g))
[ '13' ]

\d matches any digit, the exact same thing as [0-9]. \w matches any word character, the same thing as [A-Za-z] or [A-z]. \W matches any non-word character, which includes spaces and punctuation (among other things). \s matches white space. There are even more, but, well, this series is already massive, so I'll leave it to you to google for them. :)

This or That

What if I want to match something or something else?

console.log(  
    'It was the best of times. It was the worst of times'
        .match(/(best|worst)/g))
[ 'best', 'worst' ]

Just wrap the things you want to match in parentheses and separate them with a |. You can do as many as you want:

console.log(  
    'Twas bryllyg, and ye slythy toves Did gyre and gymble in ye wabe'
        .match(/(bryllyg|slythy|toves|gyre)/g))
[ 'bryllyg', 'slythy', 'toves', 'gyre' ]

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

Looking for a software developer?