Search code examples
regexregex-negationregex-lookaroundsnegative-lookbehind

How to exclude a string in the middle of a RegEx string?


I have a lot of PHP class files, that contain methods like findFoo(). I want to find (with the RegEx search of my IDE or with grep) all these occurences, in order to replace them by find(). A proper RegEx for that would be find[a-zA-Z0-9]+\(. But there are some methods (e.g. findBarByBuz()) I'd like to exclude from my search. It's the with "By" or "With" in the name.

How to build a RegEx, that matches strings like "find" + "stringWithoutByAndWithoutWith" + "("?


Solution

  • You can use negative lookahead:

    /find(?!\w*(?:by|with))\w+\(/i
    

    RegEx Demo

    (?!\w*(?:by|with)) is negative lookahead to fail the match when by or with is found after 0 or more word character. \w is equivalent to [a-zA-Z0-9_].

    /i is for case insensitive matching.