http://www.perlmonks.org?node_id=676711


in reply to search for exact string

Hi try this,

use strict; my $toFind="String"; while(<DATA>){ my $line=$_; chomp($line); if($line=~m/\b$toFind(?=[^\w\.]+|$)/i){ print "$line\n"; } }


__DATA__ blah blah string blah important stringstuff we wish to keep Unimportant string more stuff we wish to String.o Some more unimportant String.c

Punitha

Replies are listed 'Best First'.
Re^2: search for exact string
by oko1 (Deacon) on Mar 27, 2008 at 14:08 UTC

    I'm afraid that your solution is incorrect; "/\b$toFind(?=[^\w\.]+|$)/i" means "match, case-insensitively, a word boundary (1) followed by the content of $toFind followed by (2) EITHER one or more characters which are not 'word-building' characters or literal periods OR the end of the line" - which does not match the specification that was asked for. That is, (1) was never specified (although it was implied) and (2) is simply wrong: you used a positive look-ahead assertion where you should have used a negative look-ahead. As a result, your regex will match, e.g., 'String-' or 'string*'.

Re^2: search for exact string
by Anonymous Monk on Apr 24, 2019 at 11:08 UTC
    I copy pasted if($line=~m/\b$toFind(?=^\w\.+|$)/i) and it worked for my requirement... Thank you so much :) I will be thankfull if you also can explain how it work?

      Anonymous Monk:

      If you'd just read the other reply to the node you've resurrected, it would tell you what the regular expression means.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.