簡體   English   中英

正則表達式在字符串中查找第一個大寫字母

[英]Regex to find first capital letter occurrence in a string

我想在字符串中找到第一個大寫字母出現的索引。

例如 -

String x = "soHaM";

索引應該為此字符串返回2。 正則表達式應該在找到第一個大寫字母后忽略所有其他大寫字母。 如果沒有找到大寫字母,那么它應該返回0.請幫助。

我很確定你需要的是正則表達式 AZ \\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;
  }
}

你試過這個嗎?

只是為了好玩,一個LINQ解決方案:

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

這將返回IEnumerable<Int32> 如果你想要第一個大寫字符的索引,只需調用index.First()或只檢索LINQ中的第一個實例:

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

編輯

正如評論中所建議的,這是另一種LINQ方法(可能比我最初的建議更高效):

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

不需要正則Regex

int firstUpper = -1;
for(int i = 0; i < x.Length; i++)
{
    if(Char.IsUpper(x[i]))
    {
        firstUpper = i;
        break;
    }
}

http://msdn.microsoft.com/en-us/library/system.char.isupper.aspx

為了完整起見,這是我的LINQ方法(雖然它不是正確的工具,即使OP可以使用它):

int firstUpperCharIndex = -1;
var upperChars = x.Select((c, index) => new { Char = c, Index = index })
                  .Where(c => Char.IsUpper(c.Char));
if(upperChars.Any())
    firstUpperCharIndex = upperChars.First().Index;

首先你的邏輯失敗,如果方法在你的情況下返回0,那將意味着該列表中的第一個char在upperCase中,所以我建議找不到-1 meens,或者拋出異常。

無論如何只是使用正則表達式,因為你可能並不總是最好的選擇,而且它們非常慢並且難以閱讀,使得yoru代碼更難以使用。

無論如何,這是我的貢獻

    public static int FindFirstUpper(string text)
    {
        for (int i = 0; i < text.Length; i++)
            if (Char.IsUpper(text[i]))
                return i;

        return -1;
    }

使用循環

 int i = 0;
 for(i = 0; i < mystring.Length; i++)
 {
   if(Char.IsUpper(mystring, i))
    break;
 }

我是你應該看的價值;

使用Linq:

using System.Linq;

string word = "soHaMH";
var capChars = word.Where(c => char.IsUpper(c)).Select(c => c);
char capChar = capChars.FirstOrDefault();
int index = word.IndexOf(capChar); 

使用C#:

using System.Text.RegularExpressions;

string word = "soHaMH";
Match match= Regex.Match(word, "[A-Z]");
index = word.IndexOf(match.ToString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM