M
Martin Larsen
Hi,
One thing that puzzles me is whether it is possible to capture each
repeated subpattern.
Here is a simple regex that will match a string consisting of individual
words:
(?\w+) ?)+
If the subject is "three little mice" the regex will match the string,
and the subpattern match ($1) would be "mice". That is, the last
subpattern match will be returned.
But what if I wanted to extract all submatches?
So that $1 = three, $2 = little and $3 = mice
It could be done by repeating an expression like this:
(?\w+) ?)?(?\w+) ?)?(?\w+) ?)?(?\w+) ?)?
as many times as needed. Each "(?\w+) ?)?" will match one optional
word, separated by a space from the next word.
But that is not an elegant solution!
So my question is: Is it in fact possible to repeat AND capture subpatterns?
Martin
One thing that puzzles me is whether it is possible to capture each
repeated subpattern.
Here is a simple regex that will match a string consisting of individual
words:
(?\w+) ?)+
If the subject is "three little mice" the regex will match the string,
and the subpattern match ($1) would be "mice". That is, the last
subpattern match will be returned.
But what if I wanted to extract all submatches?
So that $1 = three, $2 = little and $3 = mice
It could be done by repeating an expression like this:
(?\w+) ?)?(?\w+) ?)?(?\w+) ?)?(?\w+) ?)?
as many times as needed. Each "(?\w+) ?)?" will match one optional
word, separated by a space from the next word.
But that is not an elegant solution!
So my question is: Is it in fact possible to repeat AND capture subpatterns?
Martin