Javascript Regex:如何将变量放入正则表达式中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4029109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Regex: How to put a variable inside a regular expression?
提问by Adam
So for example:
例如:
function(input){
var testVar = input;
string = ...
string.replace(/ReGeX + testVar + ReGeX/, "replacement")
}
But this is of course not working :) Is there any way to do this?
但这当然行不通:) 有没有办法做到这一点?
回答by Jason McCreary
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");
Update
更新
Per some of the comments, it's important to note that you may want to escapethe variableif there is potential for malicious content (e.g. the variable comes from user input)
每一些评论,但你可能要很注意重要逃脱的变量,如果有恶意内容的潜在(例如变量来自于用户输入)
ES6 Update
ES6 更新
In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:
在 2019 年,这通常会使用模板字符串来编写,并且上面的代码已更新。原来的答案是:
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
回答by steinar
You can use the RegExp object:
您可以使用 RegExp 对象:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring
in any way you want.
然后你可以regexstring
以任何你想要的方式构建。
You can read more about it here.
您可以在此处阅读更多相关信息。
回答by zzzzBov
To build a regular expression from a variable in JavaScript, you'll need to use the RegExp
constructor with a string parameter.
要从 JavaScript 中的变量构建正则表达式,您需要使用RegExp
带有字符串参数的构造函数。
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
of course, this is a very naive example. It assumes that input
is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:
当然,这是一个非常幼稚的例子。它假定input
已为正则表达式正确转义。如果您正在处理用户输入,或者只是想让匹配特殊字符更方便,则需要转义特殊字符:
function regexEscape(str) {
return str.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&')
}
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
回答by shunryu111
if you're using es6 template literalsare an option...
如果您使用 es6模板文字是一种选择...
string.replace(new RegExp(`ReGeX${testVar}ReGeX`), "replacement")
回答by Nikita Rybak
You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX"
. You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.
您始终可以将正则表达式作为字符串,即"ReGeX" + testVar + "ReGeX"
. 您可能需要对字符串中的某些字符进行转义(例如,双引号),但在大多数情况下它是等效的。
You can also use RegExp
constructor to pass flags in (see the docs).
您还可以使用RegExp
构造函数传入标志(请参阅文档)。
回答by Ben Carp
You can create regular expressions in JS in one of two ways:
您可以通过以下两种方式之一在 JS 中创建正则表达式:
- Using regular expression literal -
/ab{2}/g
- Using the regular expression constructor -
new RegExp("ab{2}", "g")
.
- 使用正则表达式文字 -
/ab{2}/g
- 使用正则表达式构造函数 -
new RegExp("ab{2}", "g")
。
Regular expression literals are constant, and can not be used with variables. This could be achieved using the constructor. The stracture of the RegEx constructor is
正则表达式文字是常量,不能与变量一起使用。这可以使用构造函数来实现。RegEx 构造函数的结构是
new RegExp(regularExpressionString, modifiersString)
You can embed variables as part of the regularExpressionString. For example,
您可以将变量作为regularExpressionString 的一部分嵌入。例如,
var pattern="cd"
var repeats=3
new RegExp(`${pattern}{${repeats}}`, "g")
This will match any appearance of the pattern cdcdcd
.
这将匹配模式的任何外观cdcdcd
。
回答by Timothy Mitchell
accepted answer doesn't work for me and doesn't follow MDN examples
接受的答案对我不起作用并且不遵循MDN 示例
see the 'Description' section in above link
请参阅上面链接中的“说明”部分
I'd go with the following it's working for me:
我会选择以下对我有用的方法:
let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)
// that makes dynamicRegExp = /findMe/gi
回答by Jakob Sternberg
Here's an pretty useless function that return values wrapped by specific characters. :)
这是一个非常无用的函数,它返回由特定字符包装的值。:)
jsfiddle: https://jsfiddle.net/squadjot/43agwo6x/
jsfiddle: https://jsfiddle.net/squadhot/43agwo6x/
function getValsWrappedIn(str,c1,c2){
var rg = new RegExp("(?<=\"+c1+")(.*?)(?=\"+c2+")","g");
return str.match(rg);
}
var exampleStr = "Something (5) or some time (19) or maybe a (thingy)";
var results = getValsWrappedIn(exampleStr,"(",")")
// Will return array ["5","19","thingy"]
console.log(results)
回答by Abbas Habibnejad
It's only necessary to prepare the string variable first and then convert it to the RegEx.
只需先准备字符串变量,然后将其转换为 RegEx。
for example:
例如:
You want to add minLength
and MaxLength
with the variable to RegEx:
要添加minLength
和MaxLength
使用变量正则表达式:
function getRegEx() {
const minLength = "5"; // for exapmle: min is 5
const maxLength = "12"; // for exapmle: man is 12
var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
regEx = new RegExp(regEx, "g"); // now we convert it to RegEx
return regEx; // In the end, we return the RegEx
}
now if you change value of MaxLength
or MinLength
, It will change in all RegExs.
现在,如果您更改MaxLength
或 的值MinLength
,它将在所有正则表达式中更改。
Hope to be useful. Also sorry about my English.
希望有用。也对不起我的英语。