Skip to content

-w does not interact well with metacharacters #445

Description

@epa

-w is documented as matching whole words only, and that it works by wrapping the pattern in \b metacharacters. Given this, you would expect two equivalent regexps to give the same behaviour, e.g.

abc
(?:abc)

These are exactly equivalent perl5 regular expressions, but they behave differently with -w:

% mkdir n; cd n
% echo abcde >foo
% ack -w 'abc'
% ack -w '(?:abc)'
foo
1:abcde

The fix is quite simple: at present the code doesn't add the \b anchor at the start if the regexp doesn't start with a word character, ditto end. That doesn't match the documentation, which says that the regexp is wrapped with \b unconditionally. Patch to make behaviour match docs:

diff --git a/ack b/ack
index 38ba811..978d893 100644
--- a/ack
+++ b/ack
@@ -307,11 +307,9 @@ sub build_regex {

     $str = quotemeta( $str ) if $opt->{Q};
     if ( $opt->{w} ) {
-        my $pristine_str = $str;
-
         $str = "(?:$str)";
-        $str = "\\b$str" if $pristine_str =~ /^\w/;
-        $str = "$str\\b" if $pristine_str =~ /\w$/;
+        $str = "\\b$str";
+        $str = "$str\\b";
     }

     my $regex_is_lc = $str eq lc $str;

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions