简体   繁体   中英

Regex to find first capital letter occurrence in a string

I want to find the index of first capital letter occurrence in a string.

Eg -

String x = "soHaM";

Index should return 2 for this string. The regex should ignore all other capital letters after the first one is found. If there are no capital letters found then it should return 0. Please help.

I'm pretty sure all you need is the regex 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;
  }
}

Did you try this?

Just for fun, a LINQ solution:

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

This returns IEnumerable<Int32> . If you want the index of the first upper case character, simply call index.First() or retrieve only the first instance in the LINQ:

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

EDIT

As suggested in the comments, here is another LINQ method (possibly more performant than my initial suggestion):

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

No need for 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

For the sake of completeness, here's my LINQ approach(although it's not the right tool here even if OP could use it):

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;

First your logic fails, if the method returns 0 in your case it would mean the first char in that list was in upperCase, so I would recomend that -1 meens not found, or throw a exception.

Anyway just use regular expressions becasue you can is not always the best choise, plus they are pretty slow and hard to read in general, making yoru code much harder to work with.

Anyway here is my contribution

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

        return -1;
    }

Using loop

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

i is the value u should be looking at;

Using 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); 

Using C#:

using System.Text.RegularExpressions;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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