Code Refactoring
Regex is invaluable for large-scale code refactoring. Whether you're renaming variables, updating import statements, or migrating APIs, these patterns will help.
Variable and Function Renaming
Simple Rename
Find all occurrences of a variable name (as a whole word):
\boldName\bThe \b word boundaries ensure you match oldName but not oldNameSuffix or prefixOldName.
Rename with Context
Find variable declarations specifically:
\b(const|let|var)\s+oldName\bRename Object Property Access
\.oldProperty\bImport Statement Updates
ES6 Import Refactoring
Find imports from a specific module:
import\s+(?:{[^}]+}|\w+)\s+from\s+['"]@old-package['"]Extract Named Imports
import\s+{\s*(?<imports>[^}]+)\s*}\s+from\s+['"](?<module>[^'"]+)['"]CommonJS to ES6
Find require statements to convert:
const\s+(?<name>\w+)\s*=\s*require\(['"](?<module>[^'"]+)['"]\)API Migration
Update Method Calls
Migrate from old API to new:
oldApi\.oldMethod\(([^)]*)\)Replace with: newApi.newMethod($1)
Update Callback to Promise
Find callback-style code:
(\w+)\(([^,]+),\s*function\s*\((?:err,\s*)?(\w+)\)\s*{React Class to Hooks
Find this.state references:
this\.state\.(\w+)Find this.setState:
this\.setState\(\{([^}]+)\}\)String and Comment Updates
Update String Literals
Find strings containing specific text:
(['"`])([^'"`]*old-text[^'"`]*)\1Find TODO Comments
\/\/\s*TODO:?\s*(.*)Find FIXME and HACK Comments
\/\/\s*(TODO|FIXME|HACK|XXX):?\s*(.*)Type Annotations
TypeScript Type Updates
Find type annotations:
:\s*OldType\bFind generic type parameters:
<OldType(?:\s*,\s*\w+)*>Find Interface Properties
(\w+):\s*OldType;Practical Workflow
Always use version control! Before running find-and-replace across your codebase, commit your changes so you can easily revert if something goes wrong.
Step-by-Step Refactoring
- Write the pattern in RegexLens
- Test with samples from your actual codebase
- Check the explanation to ensure it matches what you expect
- Review warnings for potential issues
- Run find-and-replace in your IDE
- Run tests to verify the refactoring
IDE Integration
Most IDEs support regex find-and-replace:
- VS Code:
Ctrl/Cmd + H, click.*to enable regex - IntelliJ:
Ctrl/Cmd + R, check "Regex" checkbox - Sublime Text:
Ctrl/Cmd + H, enable regex mode
Capture Groups for Replacement
Use capture groups to preserve parts of the match:
Find:
console\.log\((['"`][^'"`]+['"`])\)Replace:
logger.info($1)This converts console.log('message') to logger.info('message').
Common Refactoring Patterns
| Task | Find Pattern | Replace |
|---|---|---|
| Rename variable | \boldName\b | newName |
| Update import path | from ['"]@old/ | from '@new/ |
| Add prefix to function | \bfunctionName\( | prefix_functionName( |
| Convert var to const | \bvar\s+ | const |
| Remove console.log | console\.log\([^)]*\);?\n? | (empty) |