Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: List-to-Range generation

by chipmunk (Parson)
on Jun 12, 2001 at 02:55 UTC ( #87672=note: print w/replies, xml ) Need Help??


in reply to List-to-Range generation

Woops, it also converts (11,2,3) to "11-3" and (1,2,30) to "1-30". :)

Here's one way to fix it:

sub num2range { local $_ = join ',' => @_; s/(?<!\d)(\d+)(?:,((??{$++1}))(?!\d))+/$1-$+/g; return $_; }
The negative look-behind at the beginning and the negative look-ahead near the end prevent the regex from matching only part of a number, like the second 1 in 11 or the 3 in 30.

Replies are listed 'Best First'.
Re: Re: List-to-Range generation
by japhy (Canon) on Jun 12, 2001 at 04:06 UTC
    D'oh. Thanks. Believe it or not, I use that look-behind and look-ahead method in another regex, to find a number in a string less than a given number.

    japhy -- Perl and Regex Hacker
Re^2: List-to-Range generation
by rmocster (Novice) on Jul 21, 2016 at 21:52 UTC
    Thanks for the code. Is there a mod to the code to convert an array with padded numbers. I like to convert (0001,0002,0003,011,012,013,015) to "0001-0003,011-013,015". Thanks a lot.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://87672]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (9)
As of 2016-12-05 19:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (91 votes). Check out past polls.