(Pssst! All the code referenced in this post can be found in https://github.com/NerdcoreSteve/regular-expressions. Pass it on!)
You might have noticed that parentheses are used for group capture and also for the regex or. What if you want to do an or and group capture in the same regex but not capture what's in the or?
console.log( 'Princess Peach rules the Mushroom Kingdom' .replace( /(Princess (?:Peach|Toadstool)) rules the (\w+) Kingdom/, 'Monarch: $1, Kingdom: $2'))
Monarch: Princess Peach, Kingdom: Mushroom
If you put
?: at the beginning of group (right after the open parenthesis) that group will be non-capturing. You can use it for an or, but it won't show up as a captured group for your replace.
Match Any Character
Match 0 or More
* character matches 0 or more instances of a thing:
console.log( [ 'Batman', 'Superman', 'The Hulk' ] .map(s => s.match(/(ma*)/)) .filter(x => x) //filters out no matches .map(x => x.input))
[ 'Batman', 'Superman' ]
The first map call gives us our regex match. The filter call removes all elements that aren't a match. The last map call gives us the actual match and not that array/object hybrid-thing that that the
match method returns.
. character matches any character at all:
console.log( 'Banana, bananas, banana, potato, banana. Aren\'t you glad bananas?' .match(/banana./gi))
[ 'Banana,', 'bananas', 'banana,', 'banana.', 'bananas' ]
* and you match any and all characters:
console.log( [ 'Trying to only match Go go', 'Go go Power Rangers!', 'Go go gadget binoculars!', 'Go Teen Titans Go!' ] .map(x => x.match(/Go go.*/)) .filter(x => x) .map(x => x.input))
[ 'Trying to only match Go go', 'Go go Power Rangers!', 'Go go gadget binoculars!' ]
You can get a slightly different result using
.+ which matches one-or-more rather than one-or-none:
console.log( [ 'Trying to only match Go go', 'Go go Power Rangers!', 'Go go gadget binoculars!', 'Go Teen Titans Go!' ] .map(x => x.match(/Go go.+/)) .filter(x => x) .map(x => x.input))
[ 'Go go Power Rangers!', 'Go go gadget binoculars!' ]
.* combination matches one or none, we grab
'Trying to only match Go go', but if we use
+ expects something to come after
'Go go', and that first sentence doesn't pass our test.
Match One or None
? pattern allows you to match one or none of something. Here we'll match an
a and some other character:
[ 'an', 'an', 'a' ]
I hope you're beginning to see just how versatile and powerful regular expressions can be.
Move on to part 6!