Regex for Code Refactoring — Find and Replace in Source Code
Practical regex patterns for code refactoring tasks: renaming variables, updating function signatures, converting between coding styles, and migrating API calls.
Detailed Explanation
Code Refactoring with Regex
Regex find-and-replace is a powerful tool for batch code transformations that are too complex for simple text search but too simple to warrant writing a custom script.
Rename Variables with Word Boundaries
Find: \boldName\b
Replace: newName
Word boundaries (\b) prevent matching substrings, so oldName in getOldName or oldNameValue will not be affected.
Convert camelCase to snake_case
Find: ([a-z])([A-Z])
Replace: $1_$2
Then lowercase the result. Converts getUserName to get_user_name.
Update Function Signatures
Adding a parameter to all calls of a function:
Find: fetchData\(([^)]+)\)
Replace: fetchData($1, { cache: true })
Convert console.log to Logger
Find: console\.log\((.+?)\)
Replace: logger.info($1)
Update Import Paths
Find: from ['"](\.\.?/components)/([^'"]+)['"]
Replace: from "@/components/$2"
Convert String Concatenation to Template Literals
You can search for string concatenation patterns using "([^"]*)" \\+ (\\w+) \\+ "([^"]*)" and convert them to template literal syntax.
Safety Tips for Code Refactoring
- Always review changes before committing
- Use version control — commit before large regex replacements
- Test with a small scope first (single file)
- Be cautious with greedy patterns in code that contains nested structures
- Consider AST-based tools (jscodeshift, ts-morph) for complex refactoring
Use Case
You are migrating a codebase from one naming convention to another, updating API call signatures across many files, converting between import styles, or performing batch updates that text search alone cannot handle.