Stupid regex problem, s/// catching extra letter

J

Jason C

I know better than to work late at night, but sometimes it just can't be helped :)

I'm doing a simple s///, converting "www." to "http://www." when "www." occurs without a preceding "http://". Here's what I'm doing:

$text = "www.example.com";
$text =~ s#[^(http://)]www\.#http://www\.#gi;
print $text;

If $text is this, though:

$text = "<div>www.example.com</div>";

the regex is catching the > in <div>, printing:

<divhttp://www.example.com</div>

Where am I screwing up?
 
J

Jason C

What you're trying to do is a zero width negative look-behind
assertion.
s#(?<!http://)www\.#http://www.#gi should do the trick.
The "(?<!...)" tells the regex engine to only match the following
pattern if it is not preceded by the pattern in the look-behind,
without capturing anything.

"perldoc perlre" has good explanations for character classes
and look-around assertions.

-Chris

Thanks for the help, Chris. Character classes aren't exactly intuitive when a symbol changes definition completely based on context, so I'm still struggling with that a little.

The modification you suggested was perfect, though! Thanks again :)
 
R

Rainer Weikusat

Jason C said:
Thanks for the help, Chris. Character classes aren't exactly
intuitive when a symbol changes definition completely based on
context, so I'm still struggling with that a little.

A character class denotes an unordered set of characters, meaning

[^http://]
[^htp:/]
[^:pppppth/]
[^:/hpt]
[^h:t/p]

all represent identical sets and they all match a single character.
But you wanted to match the string http:// and a regex matching a
string is just the string itself, IOW, THIS sequence of characters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top