Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regular expression that will allow a string with only one Capital Letter

Tags:

string

c#

regex

The string should be 6 - 20 characters in length. And it should contain 1 Capital letter.

I can do this in code using C#:

string  st = "SomeString"

Regex rg = new Regex("[A-Z]");
MatchCollection mc = rg.Matches(st);

Console.WriteLine("Total Capital Letters: " + mc.Count);

if (mc.Count > 1)
{
  return false;
}

But what i really want is a Regular expression that will match my string if it only contains one capital. The string can start with a common letter and should have only letters.

like image 295
Phoenix Avatar asked Nov 24 '25 15:11

Phoenix


1 Answers

This one will match a string that contains lowercase letters, then a single capital letter, then more lowercase letters.

^[a-z]*[A-Z][a-z]*$

You can adjust the first and last parts to include other characters as necessary, depending on your required character domain.

For all strings of length 6 to 20, containing only letters and at most one capital letter, you can use lookaheads:

(?=^[a-zA-Z]{6,20}$)^[a-z]*[A-Z][a-z]*$
like image 67
Welbog Avatar answered Nov 26 '25 04:11

Welbog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!