简体   繁体   English

Javascript:将字符串转换为正则表达式

[英]Javascript: Convert a String to Regular Expression

I want to convert a string that looks like a regular expression...into a regular expression. 我想将看起来像正则表达式的字符串转换为正则表达式。

The reason I want to do this is because I am dynamically building a list of keywords to be used in a regular expression. 我想这样做的原因是因为我正在动态构建一个在正则表达式中使用的关键字列表。 For example, with file extensions I would be supplying a list of acceptable extensions that I want to include in the regex. 例如,对于文件扩展名,我将提供一个可接受的扩展名列表,我希望将其包含在正则表达式中。

var extList = ['jpg','gif','jpg'];

var exp = /^.*\.(extList)$/;

Thanks, any help is appreciated 谢谢,任何帮助表示赞赏

You'll want to use the RegExp constructor: 您将要使用RegExp构造函数:

var extList = ['jpg','gif','jpg'];    
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');

MDC - RegExp MDC - RegExp

var extList = "jpg gif png".split(' ');
var exp = new RegExp( "\\.(?:"+extList.join("|")+")$", "i" );

Note that: 注意:

  • You need to double-escape backslashes (once for the string, once for the regexp) 你需要双重转义反斜杠(一次用于字符串,一次用于正则表达式)
  • You can supply flags to the regex (such as case-insensitive) as strings 您可以将正则表达式的标志(例如不区分大小写)作为字符串提供
  • You don't need to anchor your particular regex to the start of the string, right? 你不需要将你的特定正则表达式锚定到字符串的开头,对吗?
  • I turned your parens into a non-capturing group, (?:...) , under the assumption that you don't need to capture what the extension is. 在假设您不需要捕获扩展名的情况下,我将您的parens变成了非捕获组(?:...)

Oh, and your original list of extensions contains 'jpg' twice :) 哦,你原来的扩展名列表包含'jpg'两次:)

You can use the RegExp object: 您可以使用RegExp对象:

var extList = ['jpg','gif','jpg'];

var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$"); 

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

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