Saturday, July 11, 2009

Code I love #2: regex & verbatim string literal

A really simple regular expression to strip out anything except alpha or numeric characters. In the following example \r, \n, !! and space are all non-alpha numerics.

Example characters that this could strip out

\n = new line
\r = carriage return
\" = quotation marks
\\ = Backslash
\t = tab


...
using System.Text.RegularExpressions;

....
string input = "This \r is a !! test \n";

string output = Regex.Replace(input, @"[^a-zA-Z0-9]", string.Empty);
//output = Thisisatest



By the way, using the @ symbol in fromt of a string means that you don't have to muck around with escape characters like \[]/. This is known as a verbatim string literal. Essentiall any string where you write @" at the beginning of the text in question (and close it off with ") means that all characters inside the quotation marks are treated exactly as they are typed.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.