tags:

views:

85

answers:

3

For example,

$thisMessage contains:

<...>
<request attribs="true" text="this is a message" ...>text here too</request>
</...>

The desired output should be,

<...>
<request attribs="true" msg="this is a message" ...>text here too</request>
</...>

The "text" enclosed within '<' and '>' must be replaced and the text not within '<' '>' should not be touched.

The regex i wrote goes likes this,

$thisMessage =~ s/(<[^>]*)(text)([^<]*>)/$1msg$3/gi;

This works but, is there a better way of doing this?

-- Edit -- Is it possible to eliminate $1 and $3 from the replace part?

+1  A: 

You can make an assumption that your "text" is followed by = and " and make like this:

$thisMessage =~ s/text="/msg="/gi;

EDIT: Also if you are really only replacing XML attribute names, then you shold probably remove the "i" flag as XML attributes names are case-sensative.

EDIT: Another version that handles < and >:

$thisMessage =~ s/(?<=\<[^<>]+?)text\s*=(?=[^<>]+?>)/msg=/gi;
Superfilin
Single quotes are OK too, and avoid "footext=": `s/\btext=(['"])/msg=$1/g`
glenn jackman
nice thought... but the problem is that the program may also have to go through normal text as-well. In that case, when the regex encounters text=", this would fail. So i feel, that checks for '<' and '>' are necessary.Any ideas using advanced perl regex?
Krishna
I have added another version within the answer.
Superfilin
A: 

This:

use strict;
use warnings;

my($in) = '<request attribs="true" text="this is a message" ...>text="here too"</request>';

$in =~ s{<[^>]+\Ktext="}{msg="}g;

print $in;

produces this:

C:\Temp>perl stackoverflow.pl
<request attribs="true" msg="this is a message" ...>text="here too"</request>
C:\Temp>

The \K is the key -- see Perl's perlre page. Not sure when \K was introduced, so you may need a later version of perl; I was using perl 5.10.0

Joe Casadonte
\K is a Perl 5.10 feature, it tells the substitution operator to not count the part of the string it matched before \K. It's a built-in way to have a variable length lookbehind.
brian d foy
+4  A: 

It looks like you want to do things with XML. I find XML::Twig to be much better for this sort of thing since it already knows how to add, delete, or change attributes.

brian d foy