[英]Javascript Dynamic Regex Parsing
I'm trying to a regular expression like so 我正在尝试这样的正则表达式
var regex_pattern = '/cat|bat|dog/i';
regex = new RegExp(regex_pattern, "i");
var string = "A dog saw a cat and a bat";
string.match(regex);
But it does not seem to be parsing. 但是它似乎没有被解析。 What am I doing wrong with this expression?
这个表达方式我在做什么错?
You've put a regex literal syntax inside a string. 您已经在字符串中放置了正则表达式文字语法。 You should either use the regex literal syntax:
您应该使用regex文字语法:
var regex = /cat|bat|dog/i;
Or pass a string (without delimiters/modifiers) as the first argument to the RegExp
constructor : 或将字符串(不带定界符/修饰符)作为第一个参数传递给
RegExp
构造函数 :
var regex = new RegExp('cat|bat|dog', 'i');
Also you'll need the g
flag (global modifier) to test the regular expression against all possible matches, otherwise only the first match will be returned. 另外,您将需要
g
标志(全局修饰符)以针对所有可能的匹配项测试正则表达式,否则将仅返回第一个匹配项。
Complete example: 完整的例子:
var regex = /cat|bat|dog/ig; //or new RegExp('cat|bat|dog', 'ig');
var string = "A dog saw a cat and a bat";
var matches = string.match(regex);
matches; //["dog", "cat", "bat"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.