Home > OS >  check for exact sub string in a line
check for exact sub string in a line

Time:01-11

I am trying to check for a exact substring tool in a line. Where i am trying below reg-ex to achieve the same.

my $line = "test git_toolk_test is git";
if ($line =~ m/(\w)*tool(\w)*/){
        print "============MATCH=======\n";
    }

It matches the toolk. But in this case, i am just looking to match exact string tool. If sub string tool is present in my string, Then my if check should hit.

My above code works if i assign $line to values like :- hai_git_tool , tool_test_log.

But it also works for values like toolk_test_log , hai_git_toolget Which is not expected. Am i missing something in pattern math expression?

i also try to match other way of having my if check :- [^a-zA-z]tool[^a-zA-Z], It's not working when string starts/ends with string tool

Please help!

CodePudding user response:

bYou can just use,

if ( $line =~ /(?:\b|_)tool(?:\b|_)/ )

\b is documented as

One such sequence is \b, which matches a boundary of some sort. \b{wb} and a few others give specialized types of boundaries. (They are all described in detail starting at \b{}, \b, \B{}, \B in perlrebackslash.) Note that these don't match characters, but the zero-width spaces between characters.

Note that _ is in \w so you want to match either a boundary or a _.

CodePudding user response:

I am just looking to match exact string tool

From your examples I assume you want to match

  • tool at the beginning of the line followed by a non alphabetic character, or
  • tool at the end of the line preceded by a non alphabetic character, or
  • tool preceded by and followed by a non alphabetic character

Here is an example:

use feature qw(say);
use strict;
use warnings;
my @test_cases = ("test git_toolk_test is git",
                  "hai_git_tool", "a tool_test_log",
                  "toolk_test_log", "hai_git_toolget",
                  '${tool-install_dir}/6.4.0-2');
for my $line (@test_cases) {
    say "$line";
    if ($line =~ m/(?:^|[^a-zA-Z])tool(?:$|[^a-zA-Z])/){
        say "  --> MATCH";
    }
    else {
        say "  --> NO MATCH";
    }
}

Output:

test git_toolk_test is git
  --> NO MATCH
hai_git_tool
  --> MATCH
a tool_test_log
  --> MATCH
toolk_test_log
  --> NO MATCH
hai_git_toolget
  --> NO MATCH
${tool-install_dir}/6.4.0-2
  --> MATCH
  •  Tags:  
  • Related