Converting shell wildcards to regex

陌路散爱 提交于 2019-12-18 04:11:45

问题


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?

Note: I want a generic converter from shell wildcards to regex.


回答1:


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 function from here: http://phpjs.org/functions/preg_quote/).

Use:

var realRegex = globStringToRegex("2012-*-*.js"); //returns a RegExp object of /2012\-.*\-.*\.js/g

Here's a JS fiddle of it working:

http://jsfiddle.net/d5sdw/2/

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.




回答2:


This should be pretty close.

yourVar.match(/.*\.js$/i)

meaning

  • beginning of string is any character sequence .*
  • followed by .js in the end \.js$
  • do this case insensitive /i



回答3:


if regexp used to get boolean result (when you don't need a match result), it is better to use test method.

/.*\.js$/i.test(yourVar)



来源:https://stackoverflow.com/questions/13818186/converting-shell-wildcards-to-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!