将shell通配符转换为正则表达式 [英] Converting shell wildcards to regex
问题描述
我想使用shell通配符搜索标题,例如 * .js
, *。*。*
等。在js。事情是我循环标题列表,我需要使用js正则表达式测试过滤文件。如何以一种好的方式将shell通配符转换为正则表达式,或者是否有任何已经执行此操作的库?
I want to search for titles using shell wildcards like *.js
, *.*.*
etc. in js. The thing is I loop through a list of titles and I need to filter the files using a js regex test. How do I convert shell wildcards to regex in a good way or are there any libraries that already does that?
注意:我想要从shell通配符到regex的通用转换器。
Note: I want a generic converter from shell wildcards to regex.
推荐答案
如果你想要一个通用的转换器功能,这应该有效:
If you want a generic converter function, this should work:
function globStringToRegex(str) {
return new RegExp(preg_quote(str).replace(/\\\*/g, '.*').replace(/\\\?/g, '.'), 'g');
}
function preg_quote (str, delimiter) {
// http://kevin.vanzonneveld.net
// + original by: booeyOH
// + improved by: Ates Goral (http://magnetiq.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: preg_quote("$40");
// * returns 1: '\$40'
// * example 2: preg_quote("*RRRING* Hello?");
// * returns 2: '\*RRRING\* Hello\?'
// * example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
// * returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'
return (str + '').replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&');
}
(preg_quote函数来自: http://phpjs.org/functions/preg_quote/ )。
(preg_quote function from here: http://phpjs.org/functions/preg_quote/).
使用:
var realRegex = globStringToRegex("2012-*-*.js"); //returns a RegExp object of /2012\-.*\-.*\.js/g
这是一个工作的JS小提琴:
Here's a JS fiddle of it working:
然后您可以使用RegExp对象进行匹配:
You can then use the RegExp object to match:
if (yourString.match(realRegex)) { //do something
更新:支持单个通配符的?
。
Update: Supports ?
for single wildcard character.
基本上全部这样做是将整个字符串转换为非正则表达式,然后确保 *
映射到。*
和?
被映射到。
,因为它们是等效的。
Basically all this does is convert the whole string to non regex, and then makes sure that *
gets mapped to .*
and ?
gets mapped to .
, as they're the equivalent.
这篇关于将shell通配符转换为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!