Home: Perl Programming Help: Regular Expressions:
what does this reg exp mean?



jelena
New User

Jun 1, 2011, 5:07 PM


Views: 11594
what does this reg exp mean?

Hi, I need help understanding what does this regular expression return.

$text_file =~ s/\/\w*\.txt\//\/ZZ\.txt\//g;

Thanks!


miller
User

Jun 1, 2011, 5:13 PM


Views: 11593
Re: [jelena] what does this reg exp mean?

That's much easier to read and therefore understand if one uses a different delimiter for the regex. My preference is to use s{}{} instead of s/// any time I have forward slashes in what I'm trying to match.

That changes the regex to the following which I would hope you could read easier:


Code
$text_file =~ s{/\w*\.txt/}{/ZZ.txt/}g;


- Miller


jelena
New User

Jun 1, 2011, 5:33 PM


Views: 11588
Re: [miller] what does this reg exp mean?

Thanks a lot,
this means replace any occurrence of words ending with .txt with ZZ.txt ? Am I right, or does /ZZ have some other meaning?


miller
User

Jun 1, 2011, 6:04 PM


Views: 11584
Re: [jelena] what does this reg exp mean?

Yes, the right side of a regex is just a standard interpolated string, so ZZ means nothing special.

And yes, the left hand side is matching any word suffixed with .txt and enclosed in forward slashes /.../

Why someone would want to do such a substitution, I couldn't say though.

- M


rovf
Veteran

Jun 6, 2011, 12:51 AM


Views: 11399
Re: [miller] what does this reg exp mean?

This would translate a string such as

/foo/bar.txt/baz

into

/ZZ.txt/baz

but would keep a string such as

/foo/bar.txt

unchanged.

Since * is a greedy regexp operator, the 'g' modifier in the end of the regexp is, IMO, meaningless (which could be an indication that this regexp doesn't exactly do what the person who wrote it, had in mind).


miller
User

Jun 6, 2011, 10:28 AM


Views: 11387
Re: [rovf] what does this reg exp mean?


In Reply To
This would translate a string such as

/foo/bar.txt/baz

into

/ZZ.txt/baz


Close rovf, but the / character is not a member of the \w character class. So it would in fact translate that string into:


Code
my $text_file = '/foo/bar.txt/baz'; 
$text_file =~ s{/\w*\.txt/}{/ZZ.txt/}g;
print "$text_file\n";

=prints
/foo/ZZ.txt/baz
=cut


Agree with all other comments though.

- M


rovf
Veteran

Jun 6, 2011, 1:48 PM


Views: 11385
Re: [miller] what does this reg exp mean?

Ah, good old miller, always to the point!

Of course, you are right! Sorry, I mis-slashed. Need new spectacles, I think ;-) Thank you for pointing out my mistake!