Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that finds consecutive words with first letter capitalized

Tags:

regex

I am looking for a regex that can identify in a sentence that consecutive words in a sentence start with capital letters.

If we take the text below as an example:

The A-Z Group is a long-established market leader in the provision of information for the global air cargo community, and also for the defence and security sectors through BDEC Limited, publishers of the British Defence Equipment Catalogue and British Defence Industry Directory.

I want to be able to retrieve the following:

The A-Z Group

BDEC Limited Defence Equipment

Catalogue British Defence

IndustryDefence Industry

Is this even possible with a regex? If so, can anyone suggest one?

like image 339
dagda1 Avatar asked Nov 06 '10 12:11

dagda1


2 Answers

(Update: I misunderstood your question at first.)

A simple case is

/([A-Z][\w-]*(\s+[A-Z][\w-]*)+)/

It may need to be modified if there are special cases of different language construct.

ruby-1.9.2-p0 > %Q{The A-Z Group is a long-established market leader in the provision of information for the global air cargo community, and also for the defence and security sectors through BDEC Limited, publishers of the British Defence Equipment Catalogue and British Defence Industry Directory.}.scan(/([A-Z][\w-]*(\s+[A-Z][\w-]*)+)/).map{|i| i.first}

=> ["The A-Z Group", "BDEC Limited", "British Defence Equipment Catalogue", "British Defence Industry Directory"]

like image 68
nonopolarity Avatar answered Nov 15 '22 06:11

nonopolarity


hopefully this will do what you want, but apologies if I've misunderstood:

([A-Z][a-zA-Z0-9-]*[\s]{0,1}){2,}

The regex searches for two or more consecutive occurences of the following sequence: a capital letter followed by any amount of lowercase/uppercase/numerical/hyphen characters (alter this to any range of non-whitespace characters to suit your needs of course), followed by a whitespace character.

Edit: I know it's common sense, but just make sure that you set the regex search to be case sensitive, caught me out when I tested it :p

Edit: The above regex will, as 動靜能量 points out, match the single word THE because it doesn't enforce that at least the first two items must have a space between them. Corrected version:

([A-Z][a-zA-Z0-9-]*)([\s][A-Z][a-zA-Z0-9-]*)+
like image 31
Moonshield Avatar answered Nov 15 '22 06:11

Moonshield