正则表达式在字符串中查找第一个大写字母

Soh*_*pta 3 c# regex string .net-2.0

我想在字符串中找到第一个大写字母出现的索引.

例如 -

String x = "soHaM";
Run Code Online (Sandbox Code Playgroud)

索引应该为此字符串返回2.在找到第一个大写字母后,正则表达式应该忽略所有其他大写字母.如果没有找到大写字母,那么它应该返回0.请帮助.

Dan*_*Tao 5

我很确定你需要的是正则表达式:A-Z \p{Lu}

public static class Find
{
  // Apparently the regex below works for non-ASCII uppercase
  // characters (so, better than A-Z).
  static readonly Regex CapitalLetter = new Regex(@"\p{Lu}");

  public static int FirstCapitalLetter(string input)
  {
    Match match = CapitalLetter.Match(input);

    // I would go with -1 here, personally.
    return match.Success ? match.Index : 0;
  }
}
Run Code Online (Sandbox Code Playgroud)

你试过这个吗?

  • 看起来不错.请注意,如果您使用0作为不表示资本的返回值,则无法区分第一个字母为大写的情况和没有资本的情况 (6认同)
  • 这只适用于非重音英文字母. (2认同)

Jam*_*ill 5

只是为了好玩,一个LINQ解决方案:

string x = "soHaM";
var index = from ch in x.ToArray()
            where Char.IsUpper(ch)
            select x.IndexOf(ch);
Run Code Online (Sandbox Code Playgroud)

这回来了IEnumerable<Int32>.如果你想要第一个大写字符的索引,只需调用index.First()或检索LINQ中的第一个实例:

string x = "soHaM";
var index = (from ch in x.ToArray()
            where Char.IsUpper(ch)
            select x.IndexOf(ch)).First();
Run Code Online (Sandbox Code Playgroud)

编辑

正如评论中所建议的,这是另一种LINQ方法(可能比我最初的建议更高效):

string x = "soHaM";
x.Select((c, index) => new { Char = c, Index = index }).First(c => Char.IsUpper(c.Char)).Index;
Run Code Online (Sandbox Code Playgroud)

  • 更快:`x.Select((c,index)=> new {Char = c,Index = index}).First(c => Char.IsUpper(c.Char)).Index;` (2认同)