Page 1 of 1

need help creating the correct regex pattern

Posted: Wed Apr 08, 2009 2:38 pm
by tbarmann
I am trying to write a function that will take a string and return a substring. Best to show by example:

I want to return the first word or words in the string that are all capital letters. For example, if the string is:

This sentence HAS THREE WORDS in a row that are all caps.

I want the expression to return "HAS THREE WORDS"

If the string is
This sentence HAS THREE WORDS in a row that are all caps and ANOTHER all caps word

it should find only "HAS THREE WORDS" and ignore any other words or letters that are all
caps.

I've been trying this pattern which doesn't work:

[\bA-Z]+^[\bA-Z]

Please help!

Thanks

Re: need help creating the correct regex pattern

Posted: Wed Apr 08, 2009 2:54 pm
by prometheuzz
Try:

Code: Select all

[A-Z]+(?:\s+[A-Z]+)+

Re: need help creating the correct regex pattern

Posted: Wed Apr 08, 2009 3:28 pm
by tbarmann
Very close. But if the sentence is this:

This sentence HAS THREE WORDS In a row that are all caps.

It finds
HAS THREE WORDS I

I want only consecutive words that are all caps.

BTW, what is correct way to code this in PHP? Is this right?

function get_dateline($str) {
return preg_grep('[A-Z]+(?:\s+[A-Z]+)+',$str);
}

Re: need help creating the correct regex pattern

Posted: Wed Apr 08, 2009 3:34 pm
by prometheuzz
tbarmann wrote:Very close. But if the sentence is this:

This sentence HAS THREE WORDS In a row that are all caps.

It finds
HAS THREE WORDS I

I want only consecutive words that are all caps.
Then you need to add a word-boundary (\b) at the end.
tbarmann wrote:BTW, what is correct way to code this in PHP? Is this right?

function get_dateline($str) {
return preg_grep('[A-Z]+(?:\s+[A-Z]+)+',$str);
}
No, preg_match(...)