简体   繁体   English

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

[英]javascript syntax for regex using variable as pattern

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

Yeah, you pretty much had it. 是的,你几乎拥有它。 You just needed to pass your regex string into the RegExp constructor. 您只需将正则表达式字符串传递给RegExp构造函数即可。 You can then call its test() function. 然后,您可以调用其test()函数。

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

Hope that helps :) 希望有帮助:)

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

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/jasongennaro/ygfQ8/2/

You should not use number . 你不应该使用number Although it is not a reserved word, it is one of the predefined class/object names. 虽然它不是保留字,但它是预定义的类/对象名之一。

And your pattern is fine without turning it into a regex literal. 你的模式很好,而不会把它变成一个正则表达式的文字。

These days many people enjoy ES6 syntax with babel. 这些天很多人都喜欢用babel语言编写ES6语法。 If this is your case then there is an option without string concatenation: 如果这是你的情况,那么有一个没有字符串连接的选项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM