Regex that finds consecutive words with first letter capitalized

前端 未结 4 1587
忘了有多久
忘了有多久 2020-12-18 09:02

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:

相关标签:
4条回答
  • 2020-12-18 09:17

    (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"]

    0 讨论(0)
  • 2020-12-18 09:19
    $mystring = "the United States of America has many big cities like New York and Los Angeles, and others like Atlanta";
    
    @phrases = $mystring =~ /[A-Z][\w'-]\*(?:\s+[A-Z][\w'-]\*)\*/g;
    
    print "\n" . join(", ", @phrases) . "\n\n# phrases = " . scalar(@phrases) . "\n\n";
    

    OUTPUT:

    $ ./try_me.pl
    
    United States, America, New York, Los Angeles, Atlanta
    
    \# phrases = 5
    
    0 讨论(0)
  • 2020-12-18 09:27

    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-]*)+
    
    0 讨论(0)
  • 2020-12-18 09:31

    Start off by thinking in non-technical terms. What do you want? A "word" followed by one or more groups of "a word separator followed by a word"

    Now you just need to define the pattern for a "word" and a "word separator", and then combine those into a complete pattern.

    When you break it down like that, a complex regex is nothing more than a few very simple pattern groups.

    0 讨论(0)
提交回复
热议问题