JJunior
JJunior

Reputation: 2849

check character by character using regex

I am trying to write a regex expression for identifying alphabets in a string. I need to go character by character for using it in my program in C#

String originalData = "90123Abc";
Regex _regex = new Regex(@"[a-zA-Z]$");

foreach (char c in originalData)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(c, _regex))
    {
        System.Console.WriteLine("  (match for '{0}' found)", _regex);
    }
    else
    {
        System.Console.WriteLine();
    }    
}

Is it possible to check character by character using regex? If not how could I go about it?

Upvotes: 1

Views: 12024

Answers (3)

jwatts1980
jwatts1980

Reputation: 7346

Try this:

foreach (Match m in Regex.Matches(originalData, @"[a-zA-Z]{1}")) 
         Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);

[a-zA-Z]{1} will look anywhere in the string to find single upper or lowercase letters. And as a bonus the matches will be in order from left to right. So looping through the matches will give you each single letter in the string.

Upvotes: 0

DotNetUser
DotNetUser

Reputation: 6612

for (int i = 0; i < input.Length; i++)
{
   if(Char.IsLetter(input[i]))
   {
    // its alphabetic
   }
}

or shortly

input.Where(c => char.IsLetter(c)).ToList()

Upvotes: 4

Mark Heath
Mark Heath

Reputation: 49482

your code will compile if you change the if statement to:

if (_regex.IsMatch(c.ToString()))

Upvotes: 0

Related Questions