More useful regular expression examples

Here are some more Regex examples that may come in handy:

// Remove Html comments
//html = Regex.Replace(html, @"\<!--&#91;^>&#93;*-->", "");
html = Regex.Replace(html, @"\<!--.*?-->", ""); // new version!

// Validate an email address (with named groups)
Regex regex = new Regex(@"^(?<user>[^@]+)@(?<host>.+)\..+$", RegexOptions.None);
Match m = regex.Match(epost);
/* Check m.Success to decide if valid or not */

// Validate a Swedish zip code ("postnummer")
regex = new Regex(@"^(\d\d\d \d\d|\d\d\d\d\d)$", RegexOptions.None);
m = regex.Match(postnummer);

In the first example, note .*? sequence. The question mark makes the match lazy, as opposed to the default greedy matching strategy. This makes a difference when there’s more than one comment in the html string. In my first try above I used [^>] to avoid matching the end comment marker, with the unfortunate side effect of missing comments with tags as content.

I have also found a useful online Regex testing service here:

http://www.regexlib.com/RETester.aspx

(Update 2009-04-28: Changed service, the previous one is now unavailable…)

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.