1

I am trying to understand and practicing the following. I guess (?:s)? and s? providing the same result

  let str = "second"; 
  let res = str.match(/second(?:s)?/g);
  console.log(res); //["second"]

  let res = str.match(/seconds?/g);
  console.log(res); //["second"]

Is there any difference between them? Thanks

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
w3outlook
  • 823
  • 6
  • 16
  • 1
    There is no difference, because `?` associates with only the `s` even without the non-capturing group. Also, since the group is non-capturing, it won't do anything extra (such as capturing) other than grouping. – Sweeper Jun 19 '19 at 06:15
  • Actually [one uses 10 steps](https://regex101.com/r/N0XF8g/1), the other [uses 8 steps](https://regex101.com/r/HvQk2g/1). – Sweeper Jun 19 '19 at 06:21

2 Answers2

2

In your example, there's no real difference because the regex with ? doesn't use a capturing group either. If you placed the s inside a capturing group, added the s to the input string, and removed the global flag from the regex, then you'd see a difference:

let str = "seconds";
let res = str.match(/second(s)?/g);
console.log(res);

But no, the non-capturing group (?:) has no real difference to the optional statement ? when used in this context.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

Non-capturing group (?:...) and capturing group (...) do not have any effect if their content is only 1 character and for capturing group if you do not use back reference to it.

You usually use groups when you want to extend the effect of quantifiers (?, {N}, {N,M}, +, *) to not only the preceding character but to several ones (the group).

Examples:

secon(ds)?
secon(?:ds)?

will both match

secon

and

seconds

Because ? will affect both d and s, in this case it will give a different result than seconds?.


Another use of groups is when you want to use alternatives in the group:

time in (?:seconds?|hours?|minutes?) is a good example

and

time in second is a good example
time in seconds is a good example
time in hours is a good example
time in hour is a good example
time in minute is a good example
time in minutes is a good example

where you put alternatives between second(s), hour(s) and minute(s) within the group


Last but not least backreferences:

Find the words for which the first char is the same as the last one

^(\w)\w*\1$

and input:

aba
aaabbba
test
apple
car

where the first three lines will match. demo: https://regex101.com/r/nrDCvn/1

Allan
  • 12,117
  • 3
  • 27
  • 51