Sunday, 19 June 2016

javascript - Is there a difference between d and d+?




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;


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...