Posts

Showing posts with the label regular expressions

Validating a Guid in C#

Oftentimes you find a need to validate if a string is a valid Guid or not. Luckily for us .net offers some excellent regular expression tools. I've found the best way to do this is to place a small static function in a helper class that validates a string passed in using a regular expression. All regular expression stuff is location in the using System.Text.RegularExpressions namespace. So in some class simply call use the following code: /// <summary> /// Determines whether the specified string is GUID. /// </summary> /// <param name="guid">The GUID.</param> /// <returns> /// <c>true</c> if the specified string is GUID; otherwise, <c>false</c>. /// </returns> public static bool IsGuid( String guid ) { if( guid != null ) { return Regex.IsMatch( guid, @"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$" ); } return fals...

String.Replace vs Regex.Replace

Image
I recently ran into a situation where I had to do some string manipulation. I had to replace some bad text with valid text. All this had to do with creating valid xml element names. So we had to string white space and some other invalid characters and replace them with valid xml element formatting. To do this we ended up using the Regex.Replace static method. Simply because there was some complexity involved that would have entailed using more then 1 String.Replace call when we can do it all with one regular expression. This caused some discussion about how heavy the regex class is and when to use it. I decided to do some testing and these are my results. First the code static void Main( string[] args ) { // this is our test value string testValue = "This is a test string"; int count; // run the regex replace DateTime regexStart = DateTime.Now; for( count = 0; count < 10000000; count++ ) { string newValue = Regex.Replace( testValue, ...

Validating an email address with a regular expression

Below is a quick and dirty post on how to use the C# regular expression library to validate an email address. The regular expression stuff is located in the System.Text.RegularExpression namespace. So somewhere in my class I use the code below. Now you don't have to do class member variables. You could just do all this code in a function. I however will be doing multiple validations so I don't want to be destroying/creating multiple objects during the life of my class. You have to create your regular expression and then use that expression when creating the RegEx object. private string _expression = @"^([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})(\]?)$"; private Regex _validEmailRegEx = new RegEx( _expression ); Then in my class I define a function that uses the RegEx object to validate an email address bein...