27276 total geeks with 3532 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
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Dec 31
December Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
Oracle, the King of
Cloud? Maybe in
Ellison"s world
Google swears no
search leg up for
new dot-word sites:
We drill into
claims
Scrooges rejoice!
Beancounters find
formula for perfect
Xmas party
Social sniffer
predicts which
Nigerian prince has
the best chance of
scamming you
Judge bars dead
Steve Jobs from
appearing on TV
news FROM BEYOND
THE GRAVE
Softlayer hops into
Equinix"s Cloud
Exchange
Bill cram woes
piling up for
Sprint: Campaigners
lob in a sueball
Singapore startup
does an Uber on
tech support
URL LOL: Delta
splats web flight
boarding pass snoop
bug
Nork-ribbing flick
The
Interview
AXED:
Sony caves under
hack terror
"menace"
Slashdot
RFID-Blocking
Blazer and Jeans
Could Stop Wireless
Identity Theft
Terrestrial Gamma
Ray Bursts Very
Common
Over 9,000 PCs In
Australia Infected
By TorrentLocker
Ransomware
Over 9,000 PCs In
Australia Infected
By TorrentLocker
Ransomware
Google Proposes To
Warn People About
Non-SSL Web Sites
Startup Magic Leap
Hires Sci-Fi Writer
Neal Stephenson As
Chief Futurist
Navy Develops a
Shark Drone For
Surveillance
Google Strikes Deal
With Verizon To
Reduce Patent Troll
Suits
Top Five Theaters
Won"t Show "The
Interview" Sony
Cancels Release
NASA Tests
Feasibility of 3D
Printing on the
Moon and Other
Planets
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 146902 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-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-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
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
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
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-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-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
Anonymous
2009-12-13 07:58:57
Gracias! A very useful post indeed! <a href="http://www.luxurydrugrehab.com/drug-rehab/">Drug Rehab</a>
Anonymous
2009-12-13 08:00:04
Gracias! A very useful post indeed! Drug Rehab
Anonymous
2010-01-08 12:14:00
An excelent post, you are a very nice at dong this.
Como ganar mas dinero
Como ganar mas dinero
Anonymous
2010-01-15 08:25:24
good
Anonymous
2010-01-25 21:35:07
I'll be using this one on http://localndex.com
Anonymous
2010-02-08 11:03:54
I must say that this is a great post. I loved reading it. You have done a great job.
Offset Printing
Anonymous
2010-02-11 11:26:02

I must say that this is a great post. I loved reading it. You have done a great job.
Spa NYC
Anonymous
2010-02-17 18:46:56
Anonymous
2010-03-16 21:58:39
Thanks mate! SEO Results
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