How to use a variable inside a regular expression
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Using a variable inside a regular expression is straightforward once you separate two cases: the variable is literal text that must be escaped, or the variable is intentional regex syntax that you want the engine to interpret. Most bugs come from mixing those two cases together.
In practice, the safe default is to treat runtime input as literal text and escape it before building the pattern. The rest of the expression can still use normal regex syntax around that escaped fragment.
JavaScript: Use RegExp, Not a Regex Literal
A JavaScript regex literal is fixed at parse time, so this does not interpolate a variable:
When part of the pattern is dynamic, build it with new RegExp(...) instead.
The escapeRegex helper is the important part. Without it, the . in item.1 would mean "any character" instead of a literal dot.
Python: Use re.escape for Literal Input
Python has the same rule, but the standard library already provides the escape helper.
re.escape is usually the right answer when user input, configuration values, or file names need to appear literally inside a larger regex.
Combine Literal Variables with Real Regex Syntax
Most dynamic patterns are a mix of fixed regex syntax and escaped variable content. For example, suppose you want a case-insensitive match for a configurable prefix followed by digits.
Only the variable fragment is escaped. Anchors such as ^ and $, character classes, quantifiers, and flags remain part of the regex you are intentionally writing.
When You Should Not Escape
Sometimes the variable is supposed to be regex syntax. Maybe your program lets advanced users configure a pattern such as foo|bar or \d{4}. In that case, escaping would destroy the meaning.
The right design is to decide this explicitly. Do not write code that sometimes treats input as literal and sometimes as regex syntax by accident.
A common approach is:
- user search text: escape it
- developer-authored pattern config: do not escape it
- mixed cases: store literal parts and regex parts separately
Being explicit here makes the code easier to review and much safer.
Anchors and Boundaries Still Matter
Dynamic construction does not change normal regex behavior. If you want a full-string match, add anchors. If you want a word boundary, add a word boundary. Interpolating a variable into a regex without thinking about match scope is how partial matches slip into production.
This matches the standalone word cat, not the cat inside other words.
Readability Counts
Dynamic regex code becomes hard to maintain when everything is concatenated inline. It is usually worth naming the escaped fragment and the final pattern separately.
That small refactor pays off during debugging because you can print the built pattern and inspect whether the variable was escaped correctly.
Common Pitfalls
The most common JavaScript mistake is trying to place a variable inside a regex literal. Another is forgetting to escape literal input before constructing the pattern. Developers also sometimes escape everything, including the regex syntax they actually wanted to keep, which produces patterns that never match. Finally, many dynamic regex bugs are really anchor bugs: the variable was inserted correctly, but the pattern still matched too much because boundaries were never defined.
Summary
- Treat runtime input as literal text unless you explicitly want regex syntax.
- In JavaScript, build dynamic patterns with
new RegExp(...). - Escape literal fragments with a helper such as
escapeRegexor Pythonre.escape. - Keep intentional regex syntax separate from escaped variables.
- Add anchors or boundaries so the match scope is exactly what you intend.
Related reading
- How to use Array.prototype.some with an async function?
- How to use await in a loop
- How to use begins_with in AWS DynamoDb js sdk?
- How to use Google API Client Library for JavaScript gapi with async/await?
- How to use hex color values
- How to use hex color values
- How to use kafka-node under typescript?
- How to use mongoose findOne
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.