in reply to Help composing Regex for matching only Titlecase words

There are two basic approaches you can take here
  1. Capture all words that fit your requirement and return that list
  2. Remove all words that do not fit your criterion, and return the result

In general, it is much easier to write positive regexes than negative ones, so I would use the second approach. I would do something like:

#!/usr/bin/perl use strict; use warnings; my $data = "Antler embedded in mound at South Street, Avebury, Wiltshi +re, England. Comment (lab): Collagen fraction used"; my @result; while ($data =~ /\b([A-Z][a-z]*)/g) { push @result, $1; } print join(' ', @result), "\n";

YAPE::Regex::Explain explains this as

The regular expression: (?-imsx:\b([A-Z][a-z]*)) matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- \b the boundary between a word char (\w) and something that is not a word char ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- [A-Z] any character of: 'A' to 'Z' ---------------------------------------------------------------------- [a-z]* any character of: 'a' to 'z' (0 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- ) end of grouping ----------------------------------------------------------------------

See perlretut for more details.

Replies are listed 'Best First'.
Re^2: Help composing Regex for matching only Titlecase words
by JavaFan (Canon) on Mar 03, 2011 at 21:44 UTC
    You anchor your words on just one side. Which means that if you have a sentence like "The USA is a UN member", you return "The U U". I did not get the impression that is what the OP wants.
      The OP does not include USA or UN as example text. Mine also gives results that are likely undesirable for character sequences that contain numbers or punctuation. Yours is likely no better on that front, though you did provide a disclaimer. Development of any regular expression depends strongly on what you are going to feed it - I think mine has the advantage of outputting more junk that yours would, making its weaknesses more obvious once the OP started putting it into practice.
        The OP does not include USA or UN as example text.
        Why do you think the OP had $data =~ s/[A-Z]{2,100}//; in the code he tried?