Fireside chats with ChatGPT: Regular expressions in notepad++

Search and Replace Regular expressions in notepad++

Regular expressions (regex) in Notepad++ can be incredibly powerful for searching and replacing text. Here’s a quick guide on how to use them effectively:

Accessing Regex Search and Replace

  1. Open Notepad++.
  2. Press Ctrl + H to open the “Find and Replace” dialog.
  3. At the bottom of the dialog, check the “Search Mode” section and select “Regular expression.”

Basic Regex Syntax

  • . – Matches any single character except newline.
  • * – Matches 0 or more of the preceding element.
  • + – Matches 1 or more of the preceding element.
  • ? – Matches 0 or 1 of the preceding element.
  • ^ – Matches the start of a line.
  • $ – Matches the end of a line.
  • \d – Matches any digit (0-9).
  • \w – Matches any word character (alphanumeric + underscore).
  • \s – Matches any whitespace character (spaces, tabs).
  • [abc] – Matches any single character within the brackets (e.g., a, b, or c).
  • [^abc] – Matches any single character not within the brackets.
  • (abc) – Capturing group; matches and remembers the pattern inside the parentheses.
  • \1 – Backreference to the first captured group.

Examples

1. Replace All Digits with a Dash

  • Find what: \d
  • Replace with:
  • Explanation: This will replace every digit in the document with a dash.

2. Remove All Leading Spaces

  • Find what: ^\s+
  • Replace with: (leave empty)
  • Explanation: This will remove any leading spaces at the beginning of each line.

3. Swap Two Words

  • Find what: (\w+)\s+(\w+)
  • Replace with: \2 \1
  • Explanation: This swaps the first and second words wherever they appear together separated by a space.

4. Extract Text Between Parentheses

  • Find what: \((.*?)\)
  • Replace with: $1
  • Explanation: This captures the text between parentheses and replaces the whole match with only the text inside.

5. Add Quotes Around Each Word

  • Find what: \b(\w+)\b
  • Replace with: “$1”
  • Explanation: This surrounds each word with double quotes.

Useful Tips

  • Non-greedy matching: Use *?, +?, or ?? for non-greedy matching, which matches the smallest possible amount.
  • Lookaheads and Lookbehinds: Advanced regex concepts like lookaheads ((?=…)) and lookbehinds ((?<=…)) are supported in Notepad++ for more complex pattern matching.