#!/usr/bin/perl use strict; use warnings; my $range="0-2,6-10,13,15"; my @range=split(",",$range); my $test="this is a test with more than 15 characters"; my $last=0; my $regex=""; for (@range) { if (/^(\d+)(-(\d+))?$/) { my $first=$1; my $length=1; if ($last lt $first) { $regex.="."x($last-$first); } $last=$first; if (defined ($3)) { $length=$3-$1+1; $last=$3; } $regex.="(".("."x$length).")"; } } my @matches = $test =~ /$regex/; my $n=0; for (@matches) { print ++$n." ($range[$n-1]): \"" ."$_","\"\n"; }