I want a regular expression that matches something at the beginning of a line, and then matches (and returns) all other words. For instance, given this line:
$line = "one two three etc";
I want something like this (that doesn't work):
@matches= $line=~ /^one(?:\s+(\S+))$/;
to return into @matches, the words "two", "three", "etc".
I don't want to know how to get the words. I want to do it with a regular expression. It seems so simple, but I have not been able to come with a solution.
To do that you need to use the \G
anchor that matches the position at the end of the last match. When you build a pattern with this anchor, you can obtain contiguous results:
@matches = $line =~ /(?:\G(?!\A)|^one) (\S+)/g;
You cannot have an unknown number of capture groups. If you try to repeat a capturing group, the last instance will override the contents of the capture group:
^one(?:\s+(\S+))+$
etc
Or:
^one\s+(\S+)\s+(\S+)\s+(\S+)$
two
three
etc
I suggest either capturing the entire group and then splitting by spaces:
^one\s+((?:\S+\s*)+)$
two three etc
Or you can do a global match and utilize \G
and \K
:
(?:^one|(?<!\A)\G).*?\K\S+
two
three
etc
^.*?\s\K|(\w+)
Try this.See demo.
http://regex101.com/r/lS5tT3/2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With