Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a guestbook I wrote a long while back and wanted to add some pizazz to it. I want to replace occurences of font colors (represented as  [color]some text[/color].

For example:

This is a [blue]test[/blue] [red]Hello![/red] [orange]world![/orange]
Now it won't work on all colors, I'll have them predefined. But I have no idea how the regex would work because I need it to make sure it doesn't crash.
This is a [blue]test[/blue] oops![/blue]
I would want it to match only the first time of each successful match and leave the uncessary ones as-is.

This is a [blue][red]test[/red][/blue]
It'd want it to match the OUTTER MOST. If the whole sentence is wrapped in BLUE and it has other color tags, it's all blue. Different font colors can coexist on the same line, however, if properly used. Color codes cannot overlap eachother.

Anyone have experience with this? Regexes are not my strong point.

Replies are listed 'Best First'.
Re: guestbook font [colors]
by GrandFather (Saint) on Aug 09, 2006 at 03:57 UTC

    You actually have a couple of tasks. First split your input up into sentences. That is somewhat non-trivial for a start. However, modules like Lingua::EN::Sentence help solve that problem. Once you have an array of sentences you can process each one by:

    use warnings; use strict; my @sentences = ( "This is [color]some text[/color].\n", "This is a [color]test[/color] oops![/color]\n", ); s!\[color\](.*)\[/color\]!\[blue\]$1\[/blue\]!g for @sentences; s!\[/?color\]!!g for @sentences; print for @sentences;

    Prints:

    This is [blue]some text[/blue]. This is a [blue]test oops![/blue]

    Note the second pass to clean up any old markup that got left behind.


    DWIM is Perl's answer to Gödel
      How would this work on colors embedded in each other like in my original example? Would this work?

      I don't quite understand the magic in this regex.

      Thank you!

        To get a better answer provide a better example. What does your original text look like and what do you want the new version to look like? I answered my best guess at what you might have. I can't imagine what you might expect something like:

        This is a [color][color]test[/color][/color]

        to be rendered as. There is not enough information in that to indicate how color should be replaced in each case.

        You should visit the Tutorials section, in particular Strings and Pattern Matching, Regular Expressions, and Parsing.


        DWIM is Perl's answer to Gödel