Friday, November 9, 2012

7 Regular Expressions a C# Developer Must Know

Regular expressions, aka Regex, are very commonly used by any developer no matter what language he's writing his program. Today I'll show the most useful Regex that sooner or later you will need them.

1. URL Regex:

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

Match:
http://www.codearsenal.net/


Not Match:
http://www.codearsenal.net?/



2. IP Address Regex:

^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Match:
73.180.213.135


Not Match:
255.255.255.256



3. Email Address Regex:

^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$

Match:
john@codearsenal.net


Not Match:
john@gmail?com



4. Username Regex:

^[a-z0-9_-]{3,16}$

Match:
john_detroit-13


Not Match:
this-username-is-too-long



5. Password Regex:

^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[_!@#$%^&+=]).*$

Description:

  • Password length must be at least 8 characters. 
  • Password must contain at least one lower case letter, at least one upper case letter and at least one special character.
  • Allowed aspecial characters: _!@#$%^&+=

Match:
paSS_123


Not Match:
weak_pass



6. Between Two Characters Regex:

(?<=\[)(.*?)(?=\])

Description:
Gets a string that is between two specific characters without including them, in our case these are two brackets.

Match:
[anything between these brackets]


Not Match:
no brackets here



7. File Extension Regex:

([^\s]+(\.(?i)(jpg|png|gif|bmp))$)

Description:

  • Any file name with specific extension, in our case these are image files.
  • Allowed extensions: jpg, png, gif or bmp 
  • You can change the allowed extensions in the regex on those what you need.

Match:
MyPicture.bmp


Not Match:
app.xaml



When you want to test your Regex I suggest to use Rubular online tool. It has user friendly interface and what I like the most in it is that it's showing the matching result on the fly.

And this is an example of how to use Regex in C#:

IsMatch Method:
string regexPattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";

if (Regex.IsMatch(testString, regexPattern))
    Console.WriteLine("This is an image file name.");
else
    Console.WriteLine("This is not an image file name.");


Match Method:
Regex regex = new Regex(@"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)");
Match match = regex.Match(testString);

if (match.Success)
    Console.WriteLine(match.Groups[1].Value);

No comments:

Post a Comment