tags:

views:

287

answers:

7

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:

  • ABC
  • ABc
  • ABC ABC
  • ABc Abc

But false for:

  • Abc
  • AbC
  • Abc Abc
  • Abc ABc

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.

+6  A: 

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}

Paolo Bergantino
"I am working with PHP, if it makes any difference." -- from the original question.
Amber
I had a small error in the code surrounding the checking. Fixed and it's all working now! Thxs
Darryl Hein
As I noted below, you actually only need `{2}` as well - the comma is unnecessary.
Amber
I have actually gone one further than changed the regex to [A-Z]{2,} I'm trying to determine if a string should be changed to lower case, by looking for more than 1 capital letter in a row.
Darryl Hein
+2  A: 

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

Rob
+2  A: 

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,}.*$
Steve Wortham
+2  A: 
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}.

Amber
+2  A: 

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

Alex Reynolds
Yeah, my bad otherwise. Oh well, question is posted and it might help someone else :)
Darryl Hein
+1  A: 

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].*$
sylvanaar
+1  A: 

non regex version

$str="Abccc";
$ch = substr($str,0,2);
if ( $ch == strtoupper($ch) ){
    print "ok";
}else{
    print "not ok";
}
ghostdog74
Would you need triple equal?
Darryl Hein
no need to. But if you want, you can also use strcmp() as well. check the excellent PHP documentation for more info .
ghostdog74
Both are strings and so this wouldn't be a useful test criteria. So the triple equals doesn't seem necessary, to me.
Alex Reynolds