473,657 Members | 2,832 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find urls in plain text files

What is the best regular expression for finding urls in plain text
files?
(By urls I mean http://www.something.com, but also www.something.com,
or sa***@somewhere .com)

Salve
Nov 2 '07 #1
9 5092
Salve Håkedal wrote:
What is the best regular expression for finding urls in plain text
files?
(By urls I mean http://www.something.com, but also www.something.com,
or sa***@somewhere .com)

Salve
The simplest way is to use the one thing they all have in common. ".com".

strstr($text,'. com');
Nov 2 '07 #2
Salve Håkedal wrote:
What is the best regular expression for finding urls in plain text
files?
(By urls I mean http://www.something.com, but also www.something.com,
or sa***@somewhere .com)

Salve
I've used this before, but you're probably better off making your own
expression. Note that it's really loose and will get a lot of false positives -
especially file names - and it will cause havoc if you use it on HTML source. I
deliberately did not enter any Top-Level-Domain filtering, because there are so
many of them. You can replace the [a-z]{2,5} with something like (com|net|org)
if you don't need to worry about country codes.

The following expression should find strings that satisfy these conditions:

- optionally a http protocol identifier
- optionally a username(:passw ord)@ string, which allows pretty much any
characters except for spaces and colons. This isn't RFC-standard, by the way.
- a hostname consisting of at least two and at most 34 labels, the last of which
has 2 to 5 alphabet letters (for weird new ones like aero and museum; you can
shorten it to 3 and still get the most common ones).
- optionally a path containing any characters apart from spaces, and /ending in
a non-punctuation character/. This last bit is vital because it avoids messing
up URLs at the end of a sentence.

(http:\/\/)?([^ :]+(:[^
]+)?@)?[a-z0-9]([a-z0-9i\-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?){0,32}\.[a-z]{2,5}(\/[^
]*[^" \.,;\)])?

(linebreaks are added by email client)

This is a case insensitive pattern, you'll need the i modifier.

--
Christoph Burschka
Nov 2 '07 #3
On 2007-11-02, Christoph Burschka <ch************ ****@rwth-aachen.dewrote:
Salve Håkedal wrote:
>What is the best regular expression for finding urls in plain text
files?
(By urls I mean http://www.something.com, but also www.something.com,
or sa***@somewhere .com)

Salve

I've used this before, but you're probably better off making your own
expression. Note that it's really loose and will get a lot of false positives -
especially file names - and it will cause havoc if you use it on HTML source. I
deliberately did not enter any Top-Level-Domain filtering, because there are so
many of them. You can replace the [a-z]{2,5} with something like (com|net|org)
if you don't need to worry about country codes.

The following expression should find strings that satisfy these conditions:

- optionally a http protocol identifier
- optionally a username(:passw ord)@ string, which allows pretty much any
characters except for spaces and colons. This isn't RFC-standard, by the way.
- a hostname consisting of at least two and at most 34 labels, the last of which
has 2 to 5 alphabet letters (for weird new ones like aero and museum; you can
shorten it to 3 and still get the most common ones).
- optionally a path containing any characters apart from spaces, and /ending in
a non-punctuation character/. This last bit is vital because it avoids messing
up URLs at the end of a sentence.

(http:\/\/)?([^ :]+(:[^
]+)?@)?[a-z0-9]([a-z0-9i\-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?){0,32}\.[a-z]{2,5}(\/[^
]*[^" \.,;\)])?

(linebreaks are added by email client)

This is a case insensitive pattern, you'll need the i modifier.

--
Christoph Burschka
Thanks alot! I'll study this closely

--
Salve
Nov 2 '07 #4
..oO(Chris Gorospe)
>Salve Håkedal wrote:
>What is the best regular expression for finding urls in plain text
files?
(By urls I mean http://www.something.com, but also www.something.com,
or sa***@somewhere .com)
The simplest way is to use the one thing they all have in common. ".com".

strstr($text,' .com');
What about the other TLDs? There are _some_ more ...

Micha
Nov 2 '07 #5
"Salve Håkedal" <ik************ *@slogedalen.no wrote in message
news:2-*************** ******@telenor. com...
On 2007-11-02, Christoph Burschka <ch************ ****@rwth-aachen.de>
wrote:
>The following expression should find strings that satisfy these
conditions:

- optionally a http protocol identifier
- optionally a username(:passw ord)@ string, which allows pretty much any
characters except for spaces and colons. This isn't RFC-standard, by the
way.
- a hostname consisting of at least two and at most 34 labels, the last
of which
has 2 to 5 alphabet letters (for weird new ones like aero and museum; you
can
shorten it to 3 and still get the most common ones).
- optionally a path containing any characters apart from spaces, and
/ending in
a non-punctuation character/. This last bit is vital because it avoids
messing
up URLs at the end of a sentence.

(http:\/\/)?([^ :]+(:[^
]+)?@)?[a-z0-9]([a-z0-9i\-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?){0,32}\.[a-z]{2,5}(\/[^
]*[^" \.,;\)])?

(linebreaks are added by email client)

This is a case insensitive pattern, you'll need the i modifier.

--
Christoph Burschka

Thanks alot! I'll study this closely
Does it make your eyes and ears bleed,the way it does mine?
Been doin this stuff since the 70's - but regex still makes me cry.

On that note, I am at the moment, writing a function that could sure benefit
from some regex.
I just want to see if a string starts with "http(s)://", "news:", "mailto:",
"ftp:".
That's a pretty simple regex, right?
Hoooowwww?

Nov 2 '07 #6
"Sanders Kaufman" <bu***@kaufman. netwrites:
Does it make your eyes and ears bleed,the way it does mine?
Been doin this stuff since the 70's - but regex still makes me cry.

On that note, I am at the moment, writing a function that could sure benefit
from some regex.
I just want to see if a string starts with "http(s)://", "news:", "mailto:",
"ftp:".
That's a pretty simple regex, right?
Hoooowwww?
This should get you started:

$pattern = '/^(http(s)?:\/\/|news:|mailto:| ftp:)/';

$tests = array('http://www.google.com' , 'https://www.google.com' ,
'news:comp.lang ', 'mailto:te**@no where.com',
' http://www.google.com' ,
'bad_http://www.google.com' ,
'mailtobad:fdsa ', 'ftp://ftp.host.net',
'ftpbad:', 'badftp://');

foreach($tests as $v) {
print "'".$v."'" . ' ~ ' .
(preg_match($pa ttern, $v)
? 'matches'
: 'doesn\'t match')."\n";
}
Nov 2 '07 #7
On 2007-11-02, Carl <c.******@gmail .comwrote:
"Sanders Kaufman" <bu***@kaufman. netwrites:
>Does it make your eyes and ears bleed,the way it does mine?
Been doin this stuff since the 70's - but regex still makes me cry.

On that note, I am at the moment, writing a function that could sure benefit
from some regex.
I just want to see if a string starts with "http(s)://", "news:", "mailto:",
"ftp:".
That's a pretty simple regex, right?
Hoooowwww?

This should get you started:

$pattern = '/^(http(s)?:\/\/|news:|mailto:| ftp:)/';

$tests = array('http://www.google.com' , 'https://www.google.com' ,
'news:comp.lang ', 'mailto:te**@no where.com',
' http://www.google.com' ,
'bad_http://www.google.com' ,
'mailtobad:fdsa ', 'ftp://ftp.host.net',
'ftpbad:', 'badftp://');

foreach($tests as $v) {
print "'".$v."'" . ' ~ ' .
(preg_match($pa ttern, $v)
? 'matches'
: 'doesn\'t match')."\n";
}
Thank you, Carl, for the script.

But the regexp there is as simple at I could have written myself. What
I need is something that can find urls in a text file, and convert them
to links. And by urls I mean, as I wrote in OT: http://something.org as
well as for example www.someother.anytopdm and the url in the original
text may be in parantheses or for example at the end of a sentence, so
it'll have a . in the end. So on..

Christoph Burschka's is still the most promising, but I haven't had time
to understand and to try it out yet.

Salve
Nov 3 '07 #8
Salve Håkedal <ik************ *@slogedalen.no writes:
On 2007-11-02, Carl <c.******@gmail .comwrote:
>"Sanders Kaufman" <bu***@kaufman. netwrites:
>>Does it make your eyes and ears bleed,the way it does mine?
Been doin this stuff since the 70's - but regex still makes me cry.

On that note, I am at the moment, writing a function that could sure benefit
from some regex.
I just want to see if a string starts with "http(s)://", "news:", "mailto:",
"ftp:".
That's a pretty simple regex, right?
Hoooowwww?

This should get you started:

$pattern = '/^(http(s)?:\/\/|news:|mailto:| ftp:)/';

$tests = array('http://www.google.com' , 'https://www.google.com' ,
'news:comp.lang ', 'mailto:te**@no where.com',
' http://www.google.com' ,
'bad_http://www.google.com' ,
'mailtobad:fdsa ', 'ftp://ftp.host.net',
'ftpbad:', 'badftp://');

foreach($tes ts as $v) {
print "'".$v."'" . ' ~ ' .
(preg_match($pa ttern, $v)
? 'matches'
: 'doesn\'t match')."\n";
}

Thank you, Carl, for the script.

But the regexp there is as simple at I could have written myself. What
I need ...
--8<-- message cut -->8--
Salve,

My response was a followup to Sanders, not your O.P., I assumed that
the previous posts answered you question already.

The question you posted is quite common, and google'n should turn
up enough examples that you should'nt have to do much to get it working
decently enough.

For starters, this looks promising, though I haven't tested it (from
the 1st results page of a google search)

http://immike.net/blog/2007/04/06/5-...r-should-know/

--
Hope that helps,
Carl.
Nov 3 '07 #9
Salve Håkedal:
What is the best regular expression for finding urls in plain text
files?

Matching URLs of every scheme with a single regular expression would
be
incredibly complex and complicated. For example, matching mailto URLs
would entail the notorious regular expression for matching e-mail
addresses. Even matching URLs of individual schemes would require
careful study of both RFC3986 and the specification that governs that
particular URL scheme. Moreover, if you want to turn partial URLs
such as www.example.com into complete URLs, you would need to define
your own heuristics for doing so.

Upshot is, you're in a world of hurt.

--
Jock

Nov 3 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

19
2925
by: rbt | last post by:
Here's the scenario: You have many hundred gigabytes of data... possible even a terabyte or two. Within this data, you have private, sensitive information (US social security numbers) about your company's clients. Your company has generated its own unique ID numbers to replace the social security numbers. Now, management would like the IT guys to go thru the old data and replace as many SSNs with the new ID numbers as possible. You...
4
4123
by: hoke | last post by:
I want to display plain text files in the browser. The files contain html and javascript and have a .txt extension. This works fine with files with just html. Unfortunately when showing files with javascript, I get an "error on page" warning and the page is not displayed. I suppose that when Internet Explorer discovers a <script> tag he starts to interpret it. This is not what I want. After all Internet Explorer is a browser and not an...
14
6865
by: Akseli Mäki | last post by:
Hi, Hopefully this is not too much offtopic. I'm working on a FAQ. I want to make two versions of it, plain text and HTML. I'm looking for a tool that will make a plain text doc out of the HTML doc. The HTML version doesn't have anything fancy, just internal links. So the tool must be able to delete internal links and anchors from the HTML version, but leave external links in simplified form. That is, the HTML version would say <a...
7
8307
by: AES | last post by:
Encountered a URL containing a comma the other day -- the first time I've ever noticed that, so far as I can recall. It worked fine, however, and I gather commas are legal in URLs. Out of curiosity, did a quick scan of an ASCII file of the 542 URLs in my personal bookmark file and discovered exactly 3 that contained commas (two with a single comma, one with three commas) -- so I guess they're pretty rarely used, even if legal. Seems...
10
3472
by: Eric Lindsay | last post by:
This may be too far off topic, however I was looking at this page http://www.hixie.ch/advocacy/xhtml about XHTML problems by Ian Hickson. It is served as text/plain, according to Firefox Response Headers - http://www.hixie.ch/advocacy/xhtml Date: Wed, 23 Nov 2005 21:36:06 GMT Server: Apache/1.3.33 (Unix) DAV/1.0.3 mod_fastcgi/2.4.2 mod_gzip/1.3.26.1a PHP/4.3.10 mod_ssl/2.8.22 OpenSSL/0.9.7e Vary: Accept-Encoding,User-agent
19
2356
by: Blair P. Houghton | last post by:
I'm just learning Python, so bear with. I was messing around with the webbrowser module and decided it was pretty cool to have the browser open a URL from within a python script, so I wrote a short script to open a local file the same way, using the script file as an example target: # browser-test.py import webbrowser import sys
0
1369
by: Shat T. Cat | last post by:
Hello, I have a program that I originally wrote in VB6 that breaks down plain-text Profit & Loss reports from my organization's Accounting system into separate files for each Cost Center (office or section). I post the output files on our local intranet web site for the managers to access. The brain surgeons at our headquarters reformatted the original reports so they don't fit on normal 8.5 x 11 inch paper. So, I wrote another little...
3
10478
by: AlecL | last post by:
Hi All, I am trying to capture the value of a textbox as a result of a button click event in a repeater, but it can't find the textbox. Here is what I am trying to do in the code for the click event: Dim prodkey As String = CType(FindControl("txtProductkey"), TextBox).Text.ToString() Response.Redirect("store_shoppingcart.aspx?pkey=" & prodkey)
8
2119
by: Bruno Rafael Moreira de Barros | last post by:
I have this framework I'm building in PHP, and it has Search Engine Friendly URLs, with site.com/controller/page/args... And on my View files, I have <?=$this->baseURL;?to print the base URL on the links (eg. <a href='<?=$this->baseURL;?>/controller/page/args'>Go somewhere</ a>. But on the CSS / JS files, how will I do it? I wonder, because on the View files, I can do <?=$this->baseURL;?>/css/site.css, and it will work. But images on the...
0
8385
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8821
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8602
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7316
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1601
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.