1.

Solve : Need help with regular expression?

Answer»

Anyone good with these ? I have tried and FAILED, but I am still looking.

I need a regular expression that will SUBSTITUTE occurrences of 'www' with 'http://www'

It needs to leave any existing 'http://www' alone.

So basically I have a string and it will change all www's in it.

Thanks for any guidance...now looking in some regexp libraries but have not found anything yet.Depends somewhat on where the line EXISTS and how the data is formatted.

Assuming that the www is at the start of the line you could

s/^www/http:\/\/www/g (USING sed)

This would replace only those strings where 'www' was at the start, so it would leave http://www alone.

Sorry I can't be more help though, not too good at 'complex' regex's myselfThanks for the reply. The www could be any where in a string, not necessarily at the beginning. I will play with your example though.

I found something that MIGHT be okay. Apparently javascript doesn't do look behind, which I think I would need to do this.

This page helped though : http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

I toyed with that and came up with this, which appears to work okay :

Code: [Select]var output = 'www.homepage.com www.somesite.co.uk http://www.leavemealone.com'.replace(/(http:\/\/)?www/g, function($0, $1){
return $1 ? $0 : 'http://www';
});

alert(output);
Unless anyone can come up with something better.

Cheers Why not first mask http://www. by changing it to something else, e.g. http://zzz. and then change any www. to http://www. and finally change all the instances of http://zzz. back to http://www.?



I like it, that's a nice solution which had never occurred to me. Thanks It's an old word-processing trick.



Discussion

No Comment Found