strat has asked for the wisdom of the Perl Monks concerning the following question:
I would like to do some text replacements in a string. I want to replace each corresponding [xzy] and [/xyz] to html-strings:
to:[xyz]level 1.1[/xyz] [xyz]level 1.2[/xyz]
<table><tr><td>level 1.1</td></tr></table> <table><tr><td>level 1.2</td></tr></table>
or:
to:[xyz]level 1.1 [xyz]level 2.1[/xyz] rest of 1.1 [/xyz]
<table><tr><td>level 1.1 <table><tr><td>level 2.1</td></tr></table>res +t of 1.1 </td></tr></table>
or even:
to:[xyz] error [xyz] level 1.1 [xyz] level 2.1 [/xyz] [/xyz] [xyz] level 1.2 [/xyz]
Here, the opening tag before error has no corresponding closing tag, so it should not be replaced.[xyz] error <table><tr><td>level 1.1 <table><tr><td>level 2.1 </td></t +r></table> </td></tr></table> <table><tr><td>level 1.2 </td></tr></table>
I need something like
Is this possible with regular expressions?while ($string =~ s/ \[xyz\] (text not containing [xyz] or [\/xyz]) \[\/xyz\] / "<table><tr><td>$1</td></tr></table>" /gsiex;
I've been trying to solve this with a regex for two hours by now, I even came up with code like the following ($tag contains xyz):
but this doesn't do the replacement in the correct order.while ($string =~ s/ (\[\Q$tag\E\]) (.+?) (\[\/\Q$tag\E\]) / my ($pre, $text, $post) = ($1,$2,$3); if ($text =~ m|\[\Q$tag\E\]|) { $pre.$text.$post; } else { "<table><tr><td>$text<\/td><\/tr><\/table>" } /gsiex) { 1; # do nothing }
Please, could you push me into the right direction? Or do I really have to write my own recursive descent?
Best regards,
perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: "Not containing something" in substitution
by Aristotle (Chancellor) on Aug 28, 2003 at 12:24 UTC | |
by CombatSquirrel (Hermit) on Aug 28, 2003 at 12:39 UTC | |
by Aristotle (Chancellor) on Aug 28, 2003 at 12:57 UTC | |
by BrowserUk (Patriarch) on Aug 28, 2003 at 19:14 UTC | |
by Aristotle (Chancellor) on Aug 28, 2003 at 21:33 UTC | |
by BrowserUk (Patriarch) on Aug 28, 2003 at 22:00 UTC | |
|
Re: "Not containing something" in substitution
by gjb (Vicar) on Aug 28, 2003 at 12:24 UTC | |
|
Re: "Not containing something" in substitution
by CombatSquirrel (Hermit) on Aug 28, 2003 at 12:31 UTC | |
|
Re: "Not containing something" in substitution
by Abigail-II (Bishop) on Aug 28, 2003 at 14:04 UTC |