Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I properly escape this regex in bash?

I'm trying to run grep with the following regex:

(?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\"

First try:

$ grep -r -n  -H -E (?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\" ./
    -bash: !key: event not found

Ok, so I need to escape the "!"s...

$ grep -r -n  -H -E (?<\!key:)(?<\!orKey:)(?<\!isEqualToString:)\@\"[A-Za-z0-9]*\" ./
    -bash: syntax error near unexpected token `('

Ok, so I need to escape the "("s...

$ grep -r -n  -H -E \(?<\!key:\)\(?<\!orKey:\)\(?<\!isEqualToString:\)\@\"[A-Za-z0-9]*\" ./
    -bash: !key:)(?: No such file or directory

Ok, so I need to quote the string?

$ grep -r -n  -H -E '\(?<\!key:\)\(?<\!orKey:\)\(?<\!isEqualToString:\)\@\"[A-Za-z0-9]*\"' ./

Returns no results... but I tried a simpler regex which doesn't have the negative-look-behind assertions, and it ran fine... I also used TextWrangler with this regex and it does work, so I can only assume I'm doing something wrong on the command line here.

EDIT:

If I use the -p option:

$ grep -r -n  -H -E -P '\(?<\!key:\)\(?<\!orKey:\)\(?<\!isEqualToString:\)\@\"[A-Za-z0-9]*\"' ./
grep: conflicting matchers specified

An example of file contents which should match:

NSString * foo = @"bar";

An example of file contents which should NOT match:

return [someDictonary objectForKey:@"foo"];
like image 692
Steve Avatar asked Dec 22 '22 03:12

Steve


1 Answers

At the core of it you need to quote the entire string with ''. (If you enclose with "" the ! will give you grief). Then you only need to escape internal ' within your regex (if any).

Also you want -P (perl) instead of -E (egrep) regex.

grep -r -n -H -P '(?<!key:)(?<!orKey:)(?<!isEqualToString:)\@\"[A-Za-z0-9]*\"' ./
like image 165
mathematical.coffee Avatar answered Dec 24 '22 00:12

mathematical.coffee