0

When using the following regex

([^\s]+)(\s+([^\s]+))*

to match strings like this one

\cmd 1 2

the object returned from the match contains

0: \cmd 1 2
1: \cmd
2:  2
3: 2

I noticed that when a match is contained inside round brackets it will be added a new element in the returning object but why the third element is matching 2 instead of 1?

Antonio Santoro
  • 827
  • 1
  • 11
  • 29
  • 2
    Because this is capture group 3 `([^\s]+)` nested in group 2, see https://regex101.com/r/uVGZOc/1 – The fourth bird Mar 27 '21 at 18:18
  • Capture groups always hold the last match, as FB indicates above. If you wouldn't mind posting your full specification (input string, expected match/output, a counterexample if appropriate), we can probably provide a different way to get your result. – ggorlen Mar 27 '21 at 18:18
  • You can use `(?:)` for a "non-capturing group". This will logically group together the values you want, but it won't store it in a capture variable. This is one of the tricky "gotchas" with regexes that you learn over time :) – Lou Mar 27 '21 at 18:20
  • How to capture `1` and `2` in two separate groups using the `*` quantifier? – Antonio Santoro Mar 27 '21 at 18:24
  • 2
    You cannot. You need to foresee for each potential argument a separate capture group, like `(\S+)(?:\s+(\S+))?(?:\s+(\S+))?` (note that `\S` is short for `[^\s]`). [See on regex101](https://regex101.com/r/lUHDNO/1) – trincot Mar 27 '21 at 18:25

0 Answers0