27

I have a Matlab project which I'm working on in the OSX editor TextMate. I need to find all instances of a certain word, let's say it's "foo", that is not either preceded by a "." or succeeded by a "/".

However, I cannot find any way to search for regular expressions that are negatively defined like this. Does anyone know if it is possible to search for something like "A preceded by anything other than B"?

(TextMate uses the Oniguruma regular expression library by K. Kosako.)

2 Answers 2

40

You want to use this bit of the syntax:

(?=subexp)         look-ahead
(?!subexp)         negative look-ahead
(?<=subexp)        look-behind
(?<!subexp)        negative look-behind

In your case, (?<!\.)foo(?!/)

3
  • 1
    Awesome! I overlooked those in the documentation. Thanks :)
    – Nagel
    Sep 20, 2012 at 12:33
  • This is a brilliant solution that also takes into account the occurrence of the word foo at the beginning or end of the text. Aug 24, 2019 at 23:01
  • Great information! Look behind solved a big issue for me! Checkout this
    – SaidbakR
    Apr 14, 2020 at 19:13
15

The ^ (circumflex or caret) inside square brackets negates the expression. So to find a "foo" not preceded by a "." would be:

[^.]foo
4
  • that should be (^|[^.])(foo) and also it also matched one extra character. Sep 20, 2012 at 12:25
  • Thanks, Brian! This is the variant I tried initially, but I messed up the syntax and tried ^[\.] instead of [^\.] :P
    – Nagel
    Sep 20, 2012 at 12:34
  • 1
    This won't work. You want all characters except '.' which means 'any character'. You need to escape it: (^|[^\.])(foo) May 8, 2014 at 18:02
  • 2
    [stuf] matches the letters s,t,u,f. Contents of square brackets are NOT an expression, they are a list. [^.] is anything but period. [^\.] is anything that isn't a back slash or a dot. ^ and - are the only characters that sometimes have a special meaning in [] Jan 21, 2020 at 23:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.