使用变量作为模式的正则表达式的 javascript 语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7735124/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:22:56  来源:igfitidea点击:

javascript syntax for regex using variable as pattern

javascriptregex

提问by Jamex

I have a variable patt with a dynamic numerical value

我有一个带有动态数值的变量 patt

var patt = "%"+number+":";

What is the regex syntax for using it in the test() method?

在 test() 方法中使用它的正则表达式语法是什么?

I have been using this format

我一直在使用这种格式

var patt=/testing/g;
var found = patt.test(textinput);

TIA

TIA

采纳答案by MicronXD

Yeah, you pretty much had it. You just needed to pass your regex string into the RegExp constructor. You can then call its test()function.

是的,你几乎拥有它。您只需要将正则表达式字符串传递给 RegExp 构造函数。然后你可以调用它的test()函数。

var matcher = new RegExp("%" + number + ":", "g");
var found = matcher.test(textinput);

Hope that helps :)

希望有帮助:)

回答by Gopherkhan

You have to build the regex using a regex object, rather than the regex literal.

您必须使用正则表达式对象而不是正则表达式文字来构建正则表达式。

From your question, I'm not exactly sure what your matching criteria is, but if you want to match the number along with the '%' and ':' markers, you'd do something like the following:

从您的问题来看,我不确定您的匹配标准是什么,但是如果您想将数字与 '%' 和 ':' 标记一起匹配,您可以执行以下操作:

var matcher = new RegExp("%" + num_to_match + ":", "g");

You can read up more here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

您可以在此处阅读更多信息:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

回答by Jason Gennaro

You're on the right track

你在正确的轨道上

var testVar = '%3:';

var num = 3;

var patt = '%' + num + ':';

var result = patt.match(testVar);

alert(result);

Example:http://jsfiddle.net/jasongennaro/ygfQ8/2/

示例:http : //jsfiddle.net/jasonennaro/ygfQ8/2/

You should not use number. Although it is not a reserved word, it is one of the predefined class/object names.

你不应该使用number. 尽管它不是保留字,但它是预定义的类/对象名称之一。

And your pattern is fine without turning it into a regex literal.

而且您的模式很好,无需将其转换为正则表达式文字。

回答by Daneel S. Yaitskov

These days many people enjoy ES6 syntax with babel. If this is your case then there is an option without string concatenation:

如今,许多人喜欢使用 babel 的 ES6 语法。如果这是你的情况,那么有一个没有字符串连接的选项:

const matcher = new RegExp(`%${num_to_match}:`, "g");