Find Regular Expression for words that contain only letters?

,

Problem

Return words that only contain letters a-z and A-Z.

Output

Return True or False if there’s a match.

Source Code (in C#)

static bool IsAllLetters ( string input )

{

Regex rg = new
Regex ( @”^[a-zA-Z]+$” );

return rg.IsMatch ( input );

}

Notes/Analysis of Source Code

The regular expression pattern contains: “^[a-zA-Z]+$”.

  • “^” matches the word from the beginning of the word.
  • “[a-zA-Z]” character class matches letters a – z and A – Z of the alphabets.
  • “+” quantifier
    matches 1 or more characters in the character class enclosed in the square brackets.
  • “$” matches the word to the end of the word.

Test Code (in C#)

static void TestIsAllLetters()

{

string[] words = { “.”, “a.b”, “the”, “dog”, “cat”, “!”, “1foo”, “foo2”,

“123foo”, “giant10.do*gs.dogs” };


foreach ( string word in words )

{

Console.WriteLine ( string.Format ( “Does “{0}” contain all letters? {1}”, word,

IsAllLetters ( word ) ? “Yes” : “No” ) );

}

}

Output

Leave a Reply

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

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