Perl Cotains

thomaszhwang
thomaszhwang used Ask the Experts™
on
I have a sentence x and I have a list of words.  I want to test if any of the words is in the sentence.  Can I test as follow?  Thanks.

for($i = 0; $i < $#words; $i++) {
if($sentence =~ $words[$i]) {
      //There is a match!
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2014
Top Expert 2015
Commented:
You can, if there are no metacharacters in the words,
and if words contained in other words also count as a match,
but it would be relatively inefficient to recompile the regular expressions many times.

If you are testing several different sentences with the      same list of words,
it may be more efficient to precompile the words into regular expressions:
  $_ = qr/$_/ for @words;                                                        
If you do this,      it is also easy to also deal with quoting metacharacters,
matching only complete words, and matching regardless of case at the same time
  $_ = qr/\b\Q$_\E\b/i for @words;                                              

If words in a sentence are always separated by whitespace, it may be
even faster to first build
  my %words;                                                                    
  @words{@words}=();                                                            
then check
  if( grep{defined $words{$_}}split' ',$sentence ){
    # there is a match
 }
ozo
Most Valuable Expert 2014
Top Expert 2015
Commented:
see also
perldoc -q "How do I efficiently match many regular expressions at once"

Author

Commented:
Actually there are metacharacter in the @words.  What should I do in this case?
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Author

Commented:
I just want to do a simple CONTAINS test.  Thanks.
ozo
Most Valuable Expert 2014
Top Expert 2015
Commented:
You might use the index function instead of the bind operator, or you could quote metacharacters with \Q...\E

Author

Commented:
Thanks.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial