perlguy has asked for the wisdom of the Perl Monks concerning the following question:
Given a string such as:
$number_set = "6 7 8 9 10";
I want a regular expression to do a s/// on the string so that $number_set will now contain 6-10. For the curious, this is directly related to MJD's Perl Quiz of the Week.
After about 1600 failed attempts and manipulations, I am seeking the wisdom of the Perl Monks on this question. Here is the code I have so far, that doesn't quite work:
$number_set = "6 7 8 9 10"; $number_set =~ s/ (?>(\d+)) # prevent backtracking, so that # a failed match after a '10' # won't try 1 and 0 individually (?{local $first = $1}) # set $first eq to the number # just matched ( \s # match a space ((??{++$first})) # followed by the number after # the one just matched )+ # as many times as possible, # but at least once /$1-$+/gx; # and replace it with the original $1, # a dash, and the last number matched
As of right now, this sets $number_set to "6-7 8 9 10", which tells me that it matches the 6 first, followed by the 7, but then subsequent matches for 8, 9, and 10 failed.
Any and all tips are welcome.
$sentence[-2] .= 'failed' # author's req. - dvergin 2002-11-28
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: match-time pattern interpolation
by demerphq (Chancellor) on Nov 27, 2002 at 22:01 UTC | |
by perlguy (Deacon) on Nov 27, 2002 at 22:29 UTC | |
|
Re: match-time pattern interpolation
by BrowserUk (Patriarch) on Nov 27, 2002 at 20:04 UTC | |
by perlguy (Deacon) on Nov 27, 2002 at 20:26 UTC |