Find Numbers with Regular Expressions - What does the '+' add to this?

Find Numbers with Regular Expressions - What does the '+' add to this?
0.0 0

#1

The challenge makes it clear that “the ( + ) after the selector allows this regular expression to match one or more digits”; does the ‘g’ not already do this? What is the difference between ( + ) and ‘g’ in this situation?

Thank you

Your code so far

// Setup
var testString = "There are 3 cats but 4 dogs.";

// Only change code below this line.

var expression = /\d+/g;  // Change this line

// Only change code above this line

// This code counts the matches of expression in testString
var digitCount = testString.match(expression).length;

#2

The g is an option of that regular expression object which allows that pattern to be matched globally on the applied string. Normally a regular expression object only searches between line breaks, on a single line. If a string has a new line (\n) break, it won’t go beyond that. The g allows matching in an entire collective string.

The + applies to the pattern, the options apply to the regular expression object.


#3

Thanks for the help Michael,

-what is throwing some confusion my way is when I run the expression through the var digitCount it returns [2] for both ‘d+’ and ‘d’. Shouldn’t ‘d’ return [1]?


#4

I like this site for regex confusion
https://regexr.com/

You can hover over different parts of your expression to see what exactly each part does.

In a real bind you can paste your test code into the text box to see which characters will be selected.

Granted this is not a substitute for knowing regular expressions but it sure helps when you’re stumped. I’ve actually learned quite a bit from this site.


#5

By the way:

  • d - Match every occurrence of one digit
  • d+ - Match every occurrence of one or more digit (i.e. 2, 34, 345342, …)

Here you can find a summary of the most common regex operators - MDN - Regular expression