在正则表达式中如何使用变量

在正则表达式中如何使用变量

技术背景

在 JavaScript 里,有时候我们需要在正则表达式中动态使用变量。然而,直接使用 /\sREGEX\s/g 这样的语法无法动态创建正则表达式,所以得借助 RegExp 对象来达成目标。

实现步骤

1. 运用 RegExp 构造函数

可借助 RegExp 构造函数动态创建正则表达式对象。示例如下:

1
2
3
4
5
// variable == 'REGEX'
let variable = 'REGEX';
let re = new RegExp(String.raw`\s${variable}\s`, "g");
let result = "mystring1".replace(re, "newstring");
console.log(result);

2. 处理旧浏览器或 Node.js 环境

在旧浏览器或者 Node.js 环境中,可采用如下方式:

1
2
3
4
5
// variable == 'REGEX'
var variable = 'REGEX';
var re = new RegExp("\\s" + variable + "\\s", "g");
var result = "mystring1".replace(re, "newstring");
console.log(result);

3. 转义特殊字符

当变量包含正则表达式的特殊字符时,要对其进行转义。可使用如下函数:

1
2
3
4
5
6
7
8
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

let str1 = ".";
let re = new RegExp(RegExp.quote(str1), "g");
let result = "pattern matching .".replace(re, "regex");
console.log(result);

4. 利用模板字符串

使用模板字符串能更便捷地插入变量:

1
2
3
4
5
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
let inputString = "I'm John, or johnny, but I prefer john.";
let result = inputString.replace(re, "Jack");
console.log(result);

核心代码

1. 基本的 RegExp 构造函数使用

1
2
3
4
let variable = 'REGEX';
let re = new RegExp(String.raw`\s${variable}\s`, "g");
let result = "mystring1".replace(re, "newstring");
console.log(result);

2. 转义函数

1
2
3
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

3. 模板字符串使用

1
2
3
4
5
let replaceThis = "John";
let re = new RegExp(`\\b${replaceThis}\\b`, 'gi');
let inputString = "I'm John, or johnny, but I prefer john.";
let result = inputString.replace(re, "Jack");
console.log(result);

最佳实践

1. 优先使用 String.prototype.replaceAll

自 ECMAScript 2021 起,String.prototype.replaceAll 方法可直接替换所有匹配项,无需借助正则表达式:

1
2
3
let str = "abcabc";
let result = str.replaceAll("a", "x");
console.log(result);

2. 对特殊字符进行转义

在使用变量构建正则表达式时,要确保对特殊字符进行转义,防止出现意外匹配。

常见问题

1. 特殊字符未转义

若变量包含正则表达式的特殊字符且未转义,会导致匹配结果不符合预期。比如:

1
2
3
4
let str1 = ".";
let re = new RegExp(str1, "g");
let result = "pattern matching .".replace(re, "regex");
console.log(result); // 输出结果不符合预期

解决办法是使用转义函数:

1
2
3
4
5
6
7
8
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

let str1 = ".";
let re = new RegExp(RegExp.quote(str1), "g");
let result = "pattern matching .".replace(re, "regex");
console.log(result); // 输出预期结果

2. 忘记使用 g 标志

若要替换所有匹配项,需在创建 RegExp 对象时使用 g 标志:

1
2
3
4
let str = "abcabc";
let re = new RegExp("a", "g");
let result = str.replace(re, "x");
console.log(result);

在正则表达式中如何使用变量
https://119291.xyz/posts/how-to-use-variable-in-regular-expression/
作者
ww
发布于
2025年5月26日
许可协议