Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  21] [ 2]  / answers: 1 / hits: 22450  / 8 Years ago, wed, june 29, 2016, 12:00:00

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;

More From » regex

 Answers
4

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 /1d*/g would match all sequences of digits that start with 1, and have 0 or more digits after it.


[#61574] Tuesday, June 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;