I want to get captures using regex on a string that could contain an indefinite amount of numbers. My intuition lead me to do "/\.getnumbers (\d+)+\s*/"
but that only matched the first number following the .getnumbers
command. How do I write a regex statement that will capture one or more numbers after the command separated by a simple space. For example: .getnumbers 5 4 3 2 1
would match (5) (4) (3) (2) (1)
, though the regex isn't specifically written to match 5 numbers, it could match any amount of numbers.
Asked
Active
Viewed 890 times
1

Reznor
- 1,235
- 5
- 14
- 23
2 Answers
2
You probably can't do it without postprocessing, since most regex engines don't allow an indefinite number of groups. Fortunately the postprocessing consists only of splitting by spaces.
/\.getnumbers (\d+(?: \d+)*)/

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
-
I agree that trying to have separate groups for each doesn’t make much sense, but I was unaware that “most regex engines don’t allow an indefinite number of groups.” I know that both Perl and PCRE are limited only by available virtual memory. What commonly used languages are more restrictive than that? (Thanks.) – tchrist Nov 29 '10 at 00:48
-
1@tchrist: They allow you to have an arbitrarily large, definite number of groups. But you still need one pair of `()` per group. – Ignacio Vazquez-Abrams Nov 29 '10 at 00:50
-
Ah, I see. People are always wanting `/(?:\b(\d+)\b\s*)+/` to populate more than just the `$1` which that pattern accounts for. The issue returns when they match `"12 345 523" =~ /(?:\b(?
\d+)\b\s*)+/` and now figure that `@{ $-{N} }` holds a list of all the matches. – tchrist Nov 29 '10 at 00:58
2
/\.getnumbers (\d+(?:\s+\d+)*)/
Note that you'll get all of the numbers as a single capture group. eg: "5 4 3 2 1"

Laurence Gonsalves
- 137,896
- 35
- 246
- 299