How to remove any URL within a string in Python


Question

I want to remove all URLs inside a string (replace them with "") I searched around but couldn't really find what I want.

Example:

text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/

I want the result to be:

text1
text2
text3
text4
text5
text6
1
25
7/4/2012 3:30:57 PM

Accepted Answer

Python script:

import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)

Output:

text1
text2
text3
text4
text5
text6

Test this code here.

48
7/4/2012 4:21:37 PM

the shortest way

re.sub(r'http\S+', '', stringliteral)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon