Darryl Hein
Darryl Hein

Reputation: 144987

Regex to determine if a string starts with more than one capital letter

I am trying to determine if a string has more than 1 capital letter in a row at the start of a string. I have the following regex but it doesn't work:

`^[A-Z]{2,1000}`

I want it to return true for:

But false for:

I have the 1000 just because I know the value won't be more than 1000 characters, but I don't care about restricting the length.

I am working with PHP, if it makes any difference.

Upvotes: 1

Views: 4141

Answers (8)

Jassi
Jassi

Reputation: 541

In one word here is the answer in regex.

^[A-Z]{2,} or ^[A-Z][A-Z]+ 

whichever looks easier to you :)

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342373

non regex version

$str="Abccc";
$ch = substr($str,0,2);
if ( $ch == strtoupper($ch) ){
    print "ok";
}else{
    print "not ok";
}

Upvotes: 1

Paolo Bergantino
Paolo Bergantino

Reputation: 488414

Wouldn't leaving the second one do it?

^[A-Z]{2,}

Which basically says "string starts with 2 or more capital letters"

Here's some tests with the strings you provided that should match:

>>> 'ABC'.match(/^[A-Z]{2,}/);
["ABC"]
>>> 'ABc'.match(/^[A-Z]{2,}/);
["AB"]
>>> 'ABC ABC'.match(/^[A-Z]{2,}/);
["ABC"]
>>> 'ABc Abc'.match(/^[A-Z]{2,}/);
["AB"]

And then the ones it shouldn't match for:

>>> 'Abc'.match(/^[A-Z]{2,}/);
null
>>> 'AbC'.match(/^[A-Z]{2,}/);
null
>>> 'Abc Abc'.match(/^[A-Z]{2,}/);
null
>>> 'Abc ABc'.match(/^[A-Z]{2,}/);
null

If you only want to match the first two, you can just do {2}

Upvotes: 7

sylvanaar
sylvanaar

Reputation: 8216

Since your regex works fine at finding which line begins with 2 caps, i assume you had another question.

Maybe you have case insensitve on

Try

(?-i)^[A-Z]{2,}

Or maybe you meant "match the whole line"

(?-i)^[A-Z].*$

Upvotes: 1

Alex Reynolds
Alex Reynolds

Reputation: 96937

I ran ^[A-Z]{2,} through the Regex Tester for egrep searches, and your test cases worked.

Upvotes: 3

Amber
Amber

Reputation: 526613

php > echo preg_match("/^[A-Z]{2}/", "ABc");
1
php > echo preg_match("/^[A-Z]{2}/", "Abc");
0

/^[A-Z]{2}/ seems to work for me. Since you're doing a substring match anyways, there's no need to do {2,} or {2,1000}.

Upvotes: 2

Steve Wortham
Steve Wortham

Reputation: 22220

So do you want it to match the entire line if the first 2 letters are capital? If so, this should do it...

^[A-Z]{2,}.*$

Upvotes: 2

Rob
Rob

Reputation: 2148

Try ^[A-Z][A-Z]

Upvotes: 2

Related Questions