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

Replacing string with its length in Regex

by Brovnik (Hermit)
on Jul 27, 2001 at 20:25 UTC ( [id://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.
s/(X+)/length($1)/g;
But this if course doesn't do what I need.
--
Brovnik

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;
        p

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).
      --
      Brovnik

        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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://100355]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-04-23 11:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found