-2

So I've read a lot of posts and documentation on the + operator for JS regex, but I'm still unsure of what it wouldo do.

For example, one of the websites I looked after gave the following example:

const nums = /\d+/
console.log(nums.test('456'))

Says it would look for infinite possibilites for d. But then...

const nums = /\d/
console.log(nums.test('456'))

... has the same result.

So I tried using numbers... for instance:

const nums2 = /45/
const nums 3 = /45+/
console.log(....

But testing both regex would STILL give the same result. If I put any numbers before or after 45 with or without the + it will still give me a "true" if 45 is togheter.

So can someone explain what the + symbol in regex means and it's usage in a way I can understand?

Rodhis
  • 19
  • 6
  • If you only want the test to succeed when the entire string matches the pattern, use the `^` and `$` anchors. For example, `^\d$` will only match a string consisting of a single digit. – 41686d6564 stands w. Palestine Aug 18 '22 at 20:57
  • Palestine, this is a JavaScript question, and on how the `+` operator works on regex. I'm not asking about C# or other operators such as `^` and `$`. – Rodhis Aug 18 '22 at 20:59
  • The language is irrelevant here. This applies to the regex rules used in C# as well as JavaScript. The root cause of the confusion here, I believe, is not realizing that a regex pattern can match _part of the string_. That's why you need `^` and `$` if your objective is to test the entire string, which is answered in the linked question. – 41686d6564 stands w. Palestine Aug 18 '22 at 21:05
  • It is not called an operator, but a quantifier. *`+` matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)* – Gabriele Petrioli Aug 18 '22 at 21:05

1 Answers1

0

There's no difference in the cases you tried -- if there's one digit, then there's also one or more digit, so they both match.

But if you use it together with other patterns you can have a difference.

console.log(/A\dB/.test("A123B"));
console.log(/A\d+B/.test("A123B"));

The first one is false because it only matches a single digit between A and B; the second is true because it matches any number of digits.

The difference can also be useful if you use .match() instead of .test(). This returns the part of the string that matched the regexp, and \d+ will return the entire number, while \d will just return the first digit.

Barmar
  • 741,623
  • 53
  • 500
  • 612