RegEx for "does not begin with"

dalawh picture dalawh · May 16, 2013 · Viewed 16.2k times · Source

The following checks if it begins with "End":

if [[ "$line" =~ ^End ]]

I am trying to find out how to match something that does not begin with "02/18/13". I have tried the following:

if [[ "$line" != ^02/18/13 ]]

if [[ "$line" != ^02\/18\/13 ]]

Neither of them seemed to work.

Answer

Gordon Davisson picture Gordon Davisson · May 16, 2013

bash doesn't have a "doesn't match regex" operator; you can either negate (!) a test of the "does match regex" operator (=~):

if [[ ! "$line" =~ ^02/18/13 ]]

or use the "doesn't match string/glob pattern" operator (!=):

if [[ "$line" != 02/18/13* ]]

Glob patterns are just different enough from regular expressions to be confusing. In this case, the pattern is simple enough that the only difference is that globs are expected to match the entire string, and hence don't need to be anchored (in fact, it needs a wildcard to de-anchor the end of the pattern).