Regular Expressions

Have been reading a little bit about string manipulation and in particular regular expressions. Having never used them before, I was a little unsure as to their uses and applications however they appear to be very useful indeed.

Regular Expressions allow you real control when processing text, meaning you can match/validate/replace/search even large amounts of text with relative ease. I have only scratched the surface so far, but can already imagine a number of applications for such text manipulation – not least the ‘Cipher Breaker’ program I am writing at the moment where it is necessary to perform frequency analysis and string replacement over large blocks of coded text.

The following code snippet shows how you can use a regular expression to mask a textbox, in this instance the textbox is masked xxx-xxx-xxx-xxx.

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    string strMask = "^\\d{3}-\\d{3}-\\d{3}-\\d{3}$";

    if (Regex.IsMatch(textBox1.Text, strMask))
    {
         MessageBox.Show("Format Correct");
    }
    else
    {
        MessageBox.Show("Format Incorrect, re-enter using: xxx-xxx-xxx-xxx");
    }
}

For more information about regular expressions and their uses (including language elements), see the two links below:

http://msdn.microsoft.com/en-us/library/hs600312.aspx
http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.80).aspx
http://www.regxlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5

Advertisements