简体   繁体   English

使用正则表达式逐字符检查字符

[英]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# 我需要逐个字符地在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? 如果没有,我该怎么办?

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

or shortly 或不久

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

如果将if语句更改为:

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

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. [a-zA-Z]{1}将在字符串中的任意位置查找单个大写或小写字母。 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. 因此,遍历匹配项将为您提供字符串中的每个字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM