From 9773f10b8471aa4fd3abce04d6e1d1da6b2eb1d0 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 15 Jan 2026 08:32:41 -0600 Subject: [PATCH] Add Use Negative Lookbehind Matching With ripgrep as a Unix TIL --- README.md | 3 +- ...gative-lookbehind-matching-with-ripgrep.md | 42 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 unix/use-negative-lookbehind-matching-with-ripgrep.md diff --git a/README.md b/README.md index 7e61b3e..50fa8d1 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1728 TILs and counting..._ +_1729 TILs and counting..._ See some of the other learning resources I work on: @@ -1773,6 +1773,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Unrestrict Where ripgrep Searches](unix/unrestrict-where-ripgrep-searches.md) - [Update Package Versions Known By asdf Plugin](unix/update-package-versions-known-by-asdf-plugin.md) - [Use fzf To Change Directories](unix/use-fzf-to-change-directories.md) +- [Use Negative Lookbehind Matching With ripgrep](unix/use-negative-lookbehind-matching-with-ripgrep.md) - [Use Regex Pattern Matching With Grep](unix/use-regex-pattern-matching-with-grep.md) - [View A Web Page In The Terminal](unix/view-a-web-page-in-the-terminal.md) - [View The Source For A Brew Formula](unix/view-the-source-for-a-brew-formula.md) diff --git a/unix/use-negative-lookbehind-matching-with-ripgrep.md b/unix/use-negative-lookbehind-matching-with-ripgrep.md new file mode 100644 index 0000000..0656dd3 --- /dev/null +++ b/unix/use-negative-lookbehind-matching-with-ripgrep.md @@ -0,0 +1,42 @@ +# Use Negative Lookbehind Matching With ripgrep + +The most straightforward way to use `ripgrep` is to hand it a pattern. It will +take that pattern and move forward through each file trying to find matches. + +```bash +$ rg 'TwilioClient\.new' +``` + +That will find all occurrences of `TwilioClient.new` in available project files. + +What if that pattern is too permissive though? That is going to match on +occurrences of `TwilioClient.new` as well as things like +`LoggingTwilioClient.new`. If we want to exclude the latter, there are a few +ways to do that. One of them being the use of [the _negative lookbehind_ regex +feature](https://www.pcre.org/current/doc/html/pcre2syntax.html#SEC23) that is +available with PCRE2 (Perl-Compatible Regular Expressions). + +A _negative lookbehind_ is like a standard pattern. We look forward through the +document for the base pattern (like `TwilioClient\.new`). However, once we find +that match, we then look back at the previous characters and if they match our +negative lookbehind pattern, then it is no longer a positive match. + +We can use one of the following to forms to achieve this: + +``` + (?