6

https://www.freecodecamp.com/challenges/find-numbers-with-regular-expressions

I was doing a lesson in FCC, and they mentioned that the digit selector \d finds one digit and adding a + (\d+) in front of the selector allows it to search for more than one digit.

I experimented with it a bit, and noticed that its the g right after the expression that searches for every number, not the +. I tried using \d+ without the g after the expression, and it only matched the first number in the string.

Basically, whether I use \d or \d+, as long as I have the g after the expression, It will find all of the numbers. So my question is, what is the difference between the two?

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

  var expression = /\d+/g;
  var digitCount = testString.match(expression).length;
Rion Williams
  • 69,631
  • 35
  • 180
  • 307
Travis
  • 107
  • 1
  • 1
  • 4

3 Answers3

10

The g at the end means global, ie. that you want to search for all occurrences. Without it, you'll just get the first match.

\d, as you know, means a single digit. You can add quantifiers to specify whether you want to match all the following, or a certain amount of digits afterwards.

\d means a single digit

\d+ means all sequential digits

So let's say we have a string like this:

123 456
7890123

/\d/g will match [1,2,3,4,5,6,7,8,9,0,1,2,3]

/\d/ will match 1

/\d+/ will match 123

/\d+/g will match [123,456,7890123]

You could also use /\d{1,3}/g to say you want to match all occurrences where there are from 1 to 3 digits in a sequence.

Another common quantifier is the star symbol, which means 0 or more. For example /1\d*/g would match all sequences of digits that start with 1, and have 0 or more digits after it.

Schlaus
  • 15,686
  • 10
  • 31
  • 62
3

Counting the occurrences of \d will find the number of digits in the string.

Counting the occurrences of \d+ will find the number of integers in the string.

I.E.

123 456 789

Has 9 digits, but 3 integers.

4castle
  • 28,713
  • 8
  • 60
  • 94
  • Couldn't the term *numbers* be a bit misleading, when parsing a float like 3.14 it will be considered two numbers. It's technically true that it consists of two numbers I think it's preferable to explain what the `+` does in regex syntax. – kb. Jun 29 '16 at 21:41
  • @kb. From their question, I think they understand the syntax part from their lesson and from experimentation, they are just curious about how they are different in usage. I would think some hand-waving is allowable with the semantics as long as it makes sense to everyone. – 4castle Jun 29 '16 at 21:45
1

\d means any digit from 0 to 9, the + says "one or more times".

As long as your numbers are single digit there is no difference, but in the string "I have 23 cows" and \d would match 2 alone whereas \d+ would match 23.

kb.
  • 1,885
  • 16
  • 22