Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Note that, in fact, moritz's improved version is essential—without it, your match has the potential to find your replaced text (since the s/// resets pos, so that the //g match starts all over again). For example, if you try your code (even suitably modified) on $toTranslate = 3 x 33332, then you'll get [[4]2], not [33332].

Note also that Perl goes out of its way to make sure that you can do lots of things that seem like they must be multi-step in a single statement. Thus, as moritz implicitly observed, it's probably better to write $tmpFound = length($1) (well, and use a better name) than $tmpFound = $1; $tmpFound = length($tmpFound).

UPDATE: On testing, moritz's version does the same thing. I think that you want something like

my $translated; while ( $toTranslate =~ /(.*?)((?:3{4})*)/g ) { $translated .= $1; $translated .= '[' . length($2) . ']' if $2; }

UPDATE 2: eye and AnomalousMonk pointed out a better, s///g-based solution: just omit the while.


In reply to Re: Regex exact pattern match problem! by JadeNB
in thread Regex exact pattern match problem! by Jts

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-19 23:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found