use strict; my $inputText = "word1, word2, #18abcdefgh ,word4 "; $inputText .= "word5, word6, #212abcdefghijkl ,word7\n"; print "before: $inputText\n"; my $newstr; { if ( $inputText =~ /\G#(\d)/gc ) { my $n1 = $1; if ( $inputText =~ /\G(\d{$1})/gc ) { my $n2 = $1; if ( $inputText =~ /\G(.{$1})/gc ) { print "(1) = $n1\n"; print "(2) = $n2\n"; print "(3) = $1\n"; $newstr .= "\"; } } } elsif ( $inputText =~ /\G([^#]+)/gc ) { $newstr .= $1; } else { last; } redo; } print "after: $newstr\n";