23 October 2007

Some Useful Regular Expressions

I've been sifting through a lot of strings lately and experimenting with the C#/.Net RegularExpressions name space. I have been extracting the string values from PDF files and then using the strings to make database calls.

The challenge has been to clean up the strings as the PDF software I am using doesn't do any cleanup for me when transporting the string back to C#.

The expressions I have been using are as follows*:

Regular Expression: @"^[!""#$%&'()*+,-./:;?@[\\\]_`{|}~0-9]+"
Purpose: Remove non-alpha characters from the start of a string.

Regular Expression: @"[!""#$%&'()*+,-./:;?@[\\\]_`{|}~0-9]+$"
Purpose: Remove non-alpha characters from the end of a string.

Regular Expression: @"[^ -~’]"
Purpose: Remove unprintable characters from string.

Regular Expressions: "[^0-9]"
Purpose: Remove non-numerical characters from a string. (via AnimaOnline)


For a useful Regular Expression tool, check out the RegExLib.com site that has a convenient .Net tester.

* @ in front of string to mark it as a literal

18 October 2007

C#: Using foreach with an generic list (List<t>)

The List is a fantastic class for working with lists and arrays in C#, but it does not directly expose an iEnumerator to allow the foreach command to iterate through the collection. Until today, I would use the for...next structure to cycle through the collection to access each item.

The List also exposes a ForEach method which delegates the ForEach to another method. This is good for some applications that need to share the functionality - and while I understand the use from an OO perspective - can decrease the readability of the code.

There is a better way that can make the code readable and exposes the iEnumerable method.

The List method also exposes the ToArray() method. Use this method to access the items in the collection. For instance, if you have a List<t> called strings, you can write the code as follows:

foreach(string s in strings.ToArray()) { ...looping code here... }