Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Replacing string with its length in Regex

by Brovnik (Hermit)
on Jul 27, 2001 at 20:25 UTC ( #100355=perlquestion: print w/replies, xml ) Need Help??
Brovnik has asked for the wisdom of the Perl Monks concerning the following question:

I have a sub which converts e.g.
_________XX_X_XX_________ => 2,1,2 __________XXXXX__________ => 5 ____XXXX___XXX__XXXXX____ => 4,3,5
Spec: output is comma separated list of run lengths of the 'X' parts.

The sub is :

sub template { my $r = shift; $r =~ s/^_+//; $r =~ s/_+$//; $r =~ s/_+/_/g; return join ',', map { length($_) } split(/_/,$r); }
Is there a Regex way of doing the last line ?
I'd like to be able to do e.g.
But this if course doesn't do what I need.

Replies are listed 'Best First'.
Re: Replacing string with its length in Regex
by japhy (Canon) on Jul 27, 2001 at 20:40 UTC
    You can execute code in the right-hand side of a substitution, by supplying the /e modifier.
    s/(X+)/length $1/eg;

    Jeff japhy Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: Replacing string with its length in Regex
by bikeNomad (Priest) on Jul 27, 2001 at 20:34 UTC
    Why not just:

    my $s = s/_*(X+)_*/length($1) . ','/ge; $s =~ s/,$//;
      even simpler:
      $r =~ s/(^_+|_+$)//g; $r =~ s/_+/,/g; $r =~ s/(X+)/length$1/ge;

Re: Replacing string with its length in Regex
by merlyn (Sage) on Jul 27, 2001 at 22:00 UTC
      Not homework honest.

      It is part of a Nonogram Solver/manipulator. This sub is part of the file loader. I know that nonogram solvers have been given as homework in other places, and I wrote one in C++ some time ago, but thought I would rebuild it in Perl for fun.

      This site gives more on Nonograms (also know as Paint by Numbers).

        Wow, so there is a name for the puzzles in picross! I take it the idea is to generate the number hints to a puzzle from an ascii bitmap?

        'The fickle fascination of and Everlasting God' - Billy Corgan, The Smashing Pumpkins

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://100355]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2017-08-23 01:30 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (344 votes). Check out past polls.