Wednesday, 27 November 2013

Regular Expression to check if a given string is alphabetic

using System.Text.RegularExpressions;

private bool IsAlphabetic(string s)
       Regex r = new Regex(@"^[a-zA-Z]+$");
       return r.IsMatch(s);

The regular expression defines a pattern and the IsMatch method checks the string to see if it matches the pattern. You can read the regular expression as follows:

^ – start of the string
[a..zA..Z] – single character that is a lowercase or uppercase letter
+ – repeat previous item one or more times (alphabetic character)
$ – end of the string

A string will therefore match if it is a single line of text containing at least one alphabetic character and is limited to alphabetic characters.

No comments:

Post a Comment