need help creating the correct regex pattern

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
tbarmann
Forum Newbie
Posts: 3
Joined: Wed Apr 08, 2009 2:29 pm

need help creating the correct regex pattern

Post 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
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: need help creating the correct regex pattern

Post by prometheuzz »

Try:

Code: Select all

[A-Z]+(?:\s+[A-Z]+)+
tbarmann
Forum Newbie
Posts: 3
Joined: Wed Apr 08, 2009 2:29 pm

Re: need help creating the correct regex pattern

Post 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);
}
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: need help creating the correct regex pattern

Post 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(...)
Post Reply