Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Drop in regex replacements?

by Joost (Canon)
on Sep 09, 2002 at 14:50 UTC ( [id://196288]=note: print w/replies, xml ) Need Help??


in reply to Drop in regex replacements?

Rather than explain the following snippet should give you an idea of what I'm trying to do. I just can't quite get it going and respectfully ask for the help of the monks.
Rather than explain it, here is my incomplete and untested (for lack of test data) solution:

sub replace { my ($tag,$attr,$content) = @_; $attr ||= $content; if ($tag eq 'b') { return "<b>$content</b>"; } elsif ($tag eq 'url') { return "<a href='$attr'>$content</a>"; } # etc. etc. etc. } s/\[(\w+)=?(\w*)\](\w+)\[\1\]/replace($1,$2,$3)/esg;
Hope this helps :-)

Update:
Ok, let's explain it a little anyway: I've turned your problem inside out, so you only need 1 regex and only 1 s statement. This has 3 advantages:

  • You don't have to run an additional s statement on the whole text for each new tag you decide to add.
  • You only need to update and debug 1 regular expression if you change the overall syntax.
  • You get rid of the $1 - problem.
You might need a little finetuning on this code (I haven't tested it except for syntax) but I think this is a lot easier and maintainable way of solving your problem.
-- Joost downtime n. The period during which a system is error-free and immune from user input.

Replies are listed 'Best First'.
Re: Re: Drop in regex replacements?
by IOrdy (Friar) on Sep 09, 2002 at 14:58 UTC
    Sorry, I thought it would be quite obvious because above each regex is an example of what I am parsing. :-(
    # Process Complex Tags -> [url="http://www.foo.bar.com"]foobar[/url]
    What you suggested would be longer than just cutting/pasting and running a complete regex for every tag. shame.
      Please read my above explanation for what I am doing here.

      I am changing the problem around to make it easier to maintain and expand. If you really need to have compact code, you can change the &replace sub like this:

      my %replaces = ( email => sub { "<a href=mailto:'$_[0]'>$_[1]</a>" }, url => sub { "<a href='$_[0]'>$_[1]</a>'" }, # etc etc etc ); sub replace { my ($tag,$attr,$content) = @_; $attr ||= $content; return $replaces{$tag}->($attr,$content); }
      I was merely trying to make the code as clean and clear as I could.
      -- Joost downtime n. The period during which a system is error-free and immune from user input.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-18 04:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found