Reputation: 2849
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
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
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
Reputation: 49482
your code will compile if you change the if
statement to:
if (_regex.IsMatch(c.ToString()))
Upvotes: 0