20096 total geeks with 3178 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
Domuk
No, not an issue with the PHP - I was responding to "AJAX not being cross site is annoying"
MaxMouse
Really? i thought that would only be important if the user had some kind of control over where the XML came from, if you hard code it (As in a PHP file) wouldn't that eliminate XSS attacks?
Domuk
Yes, but very, very necessary. AJAX requests run in the context of the browser, there'd be no security if it was cross-domain .
MaxMouse
AJAX not being cross site is annoying, all other scripts can be used in that way, having to resort to PHP to patch it is a shame.
SAJChurchey
thx MaxMouse

Donate
Donate and help us fund new challenges
Donate!
Due Date: Nov 30
November Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
MySpace makes peace
with Indies
Nvidia previews
next-gen Fermi GPUs
Potty-mouths
charged for Comcast
hijack
Microsoft
Silverlight - now
with hidden Windows
bias
Apple cult leader
emails outside
world
Sony demos monster
3D TV
Wrecking CRU:
hackers cause
massive climate
data breach
Skinny Acer
notebook delivers
six-day battery
life
VTOL gyro-copter
flying car mates
with killer robot
Oracle begs EC for
more time
Slashdot
iPhone Owners
Demand To See Apple
Source Code
Proton Beams Sent
Around the LHC
Microsoft"s Lack of
Nightly Builds For
IE
Some Claim Android
App Store Worse
Than iPhone"s
Climatic Research
Unit Hacked, Files
Leaked
Aging Nuclear
Stockpile Good For
Decades To Come
Netbooks Have
Higher Failure Rate
Than Laptops
Xbox Live Class
Action Being
Investigated
Patent Issued For
Podcasting
Linus Torvalds For
Nobel Peace Prize?
Article viewer

Url and Email validation using Regex

Written by:bb
Published by:bb
Published on:2004-09-22 12:37:39
Topic:Dot.Net
Search OSI about Dot.Net.More articles by bb.
 viewed 96005 times send this article printer friendly

Digg this!
    Rate this article :
A class which checks for valid urls and email addresses in C#

using System;
using System.Text.RegularExpressions;

public class GeneralValidation
{

    public static bool IsEmail(string Email)
    {
        string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
        Regex re = new Regex(strRegex);
        if (re.IsMatch(Email))
            return (true);
        else
            return (false);
    }

    public static bool IsUrl(string Url)
    {
        string strRegex = "^(https?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@
        + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184
        + "|" // allows either IP or domain
        + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www.
        + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain
        + "[a-z]{2,6})" // first level domain- .com or .museum
        + "(:[0-9]{1,4})?" // port number- :80
        + "((/?)|" // a slash isn't required if there is no file name
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        Regex re = new Regex(strRegex);

        if (re.IsMatch(Url))
            return (true);
        else
            return (false);
    }
}


Did you like this article? There are hundreds more.

Comments:
D-Cypell
2004-09-22 14:13:23
YUCK!! I hate RegEx... looks like you sat on the keyboard ;o).

I am not gonna comment on the RegEx as I dont really know it well enough but for the last part you should be able to do...

"return re.IsMatch(Url);", the if statement is not really needed.
D-Cypell
2004-09-22 14:24:35
Just thought of something else...

If string stuff in C# works anything like Java, then your isUrl method is doing a metric shitload of object creation. String concatenation is a killer. It would probably be better to do some cacheing of the strRegex (by making it an instance variable and and doing a 'is null' check before creating it again).

Even better would be to create the entire RegEx object in a static initilizer, but I cant say for certain that C# has them... anyone?
ReKleSS
2004-09-23 01:10:09
Here is the complete regex for URLs (warning: may cause brain to explode): [url]http://internet.ls-la.net/folklore/url-regexpr.html[url]
bb
2004-09-23 07:14:53
yeah, on the final version i do create the regex strings and object as static variables, available whilst the appdomain is loaded.

if i was doing a lot of string concatenation i would use the StringBuilder class, however i dont really define that output above as 'a lot', in fact its only wrapped to make it more legible
D-Cypell
2004-09-23 15:30:40
Yeah true@legible. I guess it depends how much you called it. If you used it for check emails on signups to 'tree surgeon monthly' then I guess the hit wouldnt be too great. However, use it for checking validity of every outgoing email on gmail and then you might have a problem :o).
Anonymous
2006-09-22 18:53:32
This thing rocks, thanks!

-Malachi
Anonymous
2007-01-25 04:26:49
It's still ERROR:
Example: httpwww.com.vn
It's OK.....
Anonymous
2007-03-13 09:57:19
I converted this to PHP's eregi . I get positives on http://hello
Anonymous
2007-03-14 01:20:46
hahahahhahaha so much code for such a simple task?
I can do the same in few lines hahahah

My site: http://freehosting1.net
Anonymous
2007-03-14 01:23:28
WHAT A MESS!
Anonymous
2007-03-28 04:53:03
coooooooooooooooollllllll
Anonymous
2007-04-28 06:55:49
Concatenating constant strings does not result in any code.
Anonymous
2007-05-11 06:30:47
thats great until you get to the file/directory level:

http://www.mydomain.com/spuriousfile.---@~~~###

this validates to true... not that Im going to suggest a alternate, this one is cool :)
Anonymous
2007-06-16 06:32:13
watch out the script is sucks
Anonymous
2007-07-07 14:42:01
this is my regexp for email validation
^[a-zA-Z0-9]+([_.-]?[a-zA-Z0-9]+)?@[a-zA-Z0-9]+([_-]?[a-zA-Z0-9]+)*([.]{1})[a-zA-Z0-9]+([.]?[a-zA-Z0-9]+)*$

im not sure its perfect
if somebody know the bug pls contact me at kopenk_3833@yahoo.co.id
Anonymous
2007-07-30 10:07:33
string strRegex = "^(https?://)"


It will fail to match http://
Anonymous
2007-09-05 19:07:12
Well now I know where all those broken email validation pages come from.

Read the rfc, guys. rfc-822 clearly says what valid email addresses are like. Among other things, they can contain '+' characters, which none of your regexps allow.
Anonymous
2007-10-13 15:33:53
Anonymous? Use yoyur brain,

string strRegex = "^(https?://)"

will NOT FAIL on "http://", check it before posting stupid comments :) You know regexps? So u should know what "?" means...

Peace
Anonymous
2007-10-19 06:44:00
It is good enaugh excepting 2 cases:
1. it won't match international domain name or unencoded national characters in query string (áéöä)
2. there are some urls containing double slashes and this shuld be accepted (http://www.domain.com/folder//?param=value)
Anonymous
2007-10-19 07:05:54
A possible solution for the problem mentioned above for Oracle

select * from table
where not regexp_like(webaddress,'^(https?://)?(([[:alnum:]_!~*''().&=+$%-]+: )?[[:alnum:]_!~*''().&=+$%-]+@)?(([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}|([[:alnum:]_!~*''()-]+\.)*([[:alnum:]][[:alnum:]-]{0,61})?[[:alnum:]]\.[a-z]{2,6})(:[[:digit:]]{1,4})?((/*)|(/+[[:alnum:]_!~*''().;?:@&=+$,%#-]+)+/*)$','i')
Anonymous
2007-10-19 07:34:48
And for vb.net

IsUrl = Regex.IsMatch(url, "^(https?://)?(([\w!~*'().&=+$%-]+: )?[\w!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([\w!~*'()-]+\.)*([\w^-][\w-]{0,61})?[\w]\.[a-z]{2,6})(:[0-9]{1,4})?((/*)|(/+[\w!~*'().;?:@&=+$,%#-]+)+/*)$", RegexOptions.IgnoreCase)
Anonymous
2007-12-11 20:26:00
Thank for cool regex

dave,
http://www.onlinebizbuzz.com
Anonymous
2008-02-05 13:14:18
Thanks a lot for such a nice snippet of coding. It really helped me a lot.

- Mittal Patel
http://www.share-ebooks.com
Anonymous
2008-02-07 10:09:17
Thank you for regex !

Jos
Anonymous
2008-03-27 00:34:20
Hi... the Regex for vb.net is not working for me!

why? o_O

Regrats
Anonymous
2008-03-28 19:22:31
Stop promoting your websites
Anonymous
2008-04-17 15:09:14
All are motherfucks
Anonymous
2008-04-21 16:04:54
current:: if (!preg_match("/^(http(s?):\/\/|ftp:\/\/{1})((\w+\.){1,})\w{2,}$/i", $url))


example:: if (!preg_match('^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#]+$', $url))

example:: if (!preg_match('^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+(=\w+)?)(&\w+(=\w+)?)*)?', $url))
Anonymous
2008-04-23 10:39:19
sale java main tera baap batayega....
Anonymous
2008-06-03 14:44:48
i saw a pattern @ http://www.geekzilla.co.uk/view2D3B0109-C1B2-4B4E-BFFD-E8088CBC85FD.htm

and its : https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)"

so useful.
mncvizyon.com my site
Anonymous
2008-07-13 06:31:19
Regexp is really a bonus when you are programming in soap. <a href="http://www.earthceuticals.com"> Savon naturel </ a> est faite ŕ partir d'huiles essentielles pures et les huiles végétales pures. Il n'ya pas d'animaux et pas d'ingrédients artificiels ingrédients dans <a href="http://www.earthceuticals.com"> savon naturel </ a>.
Anonymous
2008-07-14 23:57:36
This one rocks:

^(?:(?:(?i)https?(?-i):\/\/)?(?:(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{0,2})(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{0,2}|0)){3})|(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*)(?::(?:6[0-5]{0,2}[0-3]?[0-5]?|[1-5][0-9]{0,4}))?))(?:\/|(?:\/[^\s\x00-\x1f]+)+)?(?:(?:\?[^\s\x00-\x1f]+(?:=[^\s\x00-\x1f]+)(?:\&[^\s\x00-\x1f]+(?:=[^\s\x00-\x1f]+)?)*))?$
Anonymous
2008-08-06 09:05:32
jhjh
Anonymous
2008-08-20 11:49:02
Your regexp doesn't seem to support these cases, with a (possibly blank) password:
http://user:password@host.com
http://user:@host.com

Not that I expect I'll need it myself...
Anonymous
2008-08-20 11:54:29
What about national characters? For example, this is a valid URL I think:

www.host.se/Thingyĺäö.html
Anonymous
2008-09-09 08:05:44
wqw
Anonymous
2008-09-09 08:06:26
Heello
Anonymous
2008-09-11 12:41:57
Thanks a lot for such a nice snippet of coding. It really helped me a lot!

<a href="http://www.transcription.su">Alex</a>
<a href="http://www.13-kadr.ru">http://www.13-kadr.ru</a>
Anonymous
2008-09-11 12:43:29
Thanks a lot for such a nice snippet of coding. It really helped me a lot!

Alex
http://www.13-kadr.ru
skenderbeg
2008-09-12 15:25:13
I was hoping to convert this so it worked a little differently, but this is my first attempt at regex, and I'm failing miserably. I need to identify and extract a specific portion of a URL via regex, of the form:

http://www.STRING_OF_INTEREST.mywebsite.com

unfortunately, I can't get my stuff to work - anyone have an idea how I can extract the STRING_OF_INTEREST portion? The need is for mod rewrite rules in apache... so, it could start with https/http/www/WWW/etc...

thanks in advance,
skenderbeg
Anonymous
2008-09-19 06:43:58

return new Regex(strRegex).IsMatch(Url);
Anonymous
2008-09-30 23:41:51
Thank you. Your email check was the only one I could use in pl/sql
Anonymous
2008-10-27 15:11:50
I'm trying to extract the basic regex to use in a different platform. Why are some of the "@" characters *outside* the quotes in the string-concetenation? Is this a special use of "@" - I don't do C#
Anonymous
2008-11-26 16:56:22
http://www.aaaa-bbbbb.com

why this dont work ?
Anonymous
2008-11-30 12:34:45
Thank for the regex,

Regards,

Mike
http://www.growshop.com
Anonymous
2008-12-08 21:30:56
thank you so much!!!!!!!!!!!
Anonymous
2009-02-13 14:14:45
for matching ALL URIs with port numbers, the part "(:[0-9]{1,4})?" has to be changed into "(:([0-5][0-9]{1,4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5]))?"
then it will also match the port numbers from 10000 to 65535...
that regex also matches http://999.999.999.999 as an IP-adress...
and adresses with subdomains (srv.subdomain.SLD.TLD) aren't matched...
i think that regex might work on some URLs, but it's still very uncomplete
Anonymous
2009-03-30 10:41:31
Cheers

http://www.eternumonline.com
Anonymous
2009-04-01 20:46:35
Nice, thank you.
(http://www.cyclopsvue.blogspot.com)
Anonymous
2009-04-22 14:19:56
Thanks a lot for such a nice snippet of coding. It really helped me a lot. online games
Anonymous
2009-06-12 06:49:49
"www.fghf" is taking
Anonymous
2009-06-12 11:59:23
I tried a lot of regex for url validation and this is the best one i've seen.

Thanks.
Anonymous
2009-07-01 15:11:24
Thank you for this excellent working and good documented regex!!

i used it for my website
Kochrezepte
Anonymous
2009-07-10 16:36:11
What would a valu vb .net regex expression be for the following pattern:
<core:url address="somewebaddress">
e.g.
<core:url address="www.communities.gov.uk/documents/localgovernment/pdf/155181.pdf">
Anonymous
2009-07-18 09:22:44
^(http\:\/\/|[a-zA-Z0-9_\-]+(?:\.[a-zA-Z0-9_\-]+)*\.[a-zA-Z]{2,4}(?:\/[a-zA-Z0-9_]+)*(?:\/[a-zA-Z0-9_]+\.[a-zA-Z]{2,4}(?:\?[a-zA-Z0-9_]+\=[a-zA-Z0-9_]+)?)?(?:\&[a-zA-Z0-9_]+\=[a-zA-Z0-9_]+)*)$

everyone
plz follw this regular expression for url
http://www.communities.com/regexp/
or
www.communities.com

thanks from
shital jamdade
Anonymous
2009-07-20 17:33:16
Thanks. Really helpfull site.
Anonymous
2009-07-27 07:34:25
<a href="http://www.qualitycodes.com/tutorial.php?articleid=28">http://www.qualitycodes.com/tutorial.php?articleid=28</a> lists all the common regular expressions
Anonymous
2009-08-07 02:28:14
looks like you sat on the keyboard...
buy cymbalta
Anonymous
2009-08-27 00:46:47
if(p) return true; else return false;

is better written:

return p;
Anonymous
2009-10-04 13:51:56
Thank you for regex !
1000 games
Anonymous
2009-10-20 10:43:46
perhaps you could use the Uri object to check valid url:

Uri.IsWellFormedUriString("http://www.someuri.com", UriKind.RelativeOrAbsolute);
Anonymous
2009-10-21 08:27:20
Thanks.Good site.[url=http://mobile-games.bwap.org/free mobile games[/url]
Anonymous
2009-10-21 08:27:57
Thanks.Good site.free mobile games
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
bb
ASP.NET RadioButton GroupName when inside a Repeater on Sun 10th Jun 8am
I was thankful on finding this nugget of code, which makes the groupname work out when slamming in radiobuttons in an asp.net repeater. http://www.codeguru.com/csharp/csharp/cs _controls/custom/article.php/c12371/


     
Your Ad Here
 
Copyright Open Source Institute, 2006