【问题标题】:More precise wildcard regexp更精确的通配符正则表达式
【发布时间】:2018-09-21 18:16:57
【问题描述】:

我做了一个通配符过滤例程来匹配使用通配符的文件名。例如:*.js 给我一个目录下的所有 js 文件。

但是,当目录中有.json 文件时,我也会得到这些。我明白为什么,但这不是我想要的。

我使用这个(从网站上挑选的)wildcardStringToRegexp 函数来构建正则表达式(因为我不擅长这个):

function wildcardStringToRegexp( s ) 
{
    if( isValidString( s ))
     { return false; }

    function preg_quote(str, delimiter) 
    {
        // *     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'), '\\$&');
    }


    return new RegExp(preg_quote(s).replace(/\\\*/g, '.*').replace(/\\\?/g, '.'), 'g');
}

function fnmatch( sMask, sMatch, bReturnMatches )
{
    if( !isValidString( sMatch ))
     { return false; }

    var aMatches = sMatch.match( wildcardStringToRegexp( sMask ) );

    if( bReturnMatches )
     { return isValidArray( aMatches )?aMatches:[]; }

    return isValidArray( aMatches )?aMatches.length:0;
}  

例如:

fnmatch( '*.js', 'myfile.js' )   returns 1
fnmatch( '*.js', 'myfile.json' ) returns 1 , this is not what I want

如何更改wildcardStringToRegexp() 函数,或者我需要更改什么fnmatch( '*.js', 'myfile.json' ) 是不可能的,无效所以fnmatch 更精确?

【问题讨论】:

  • 不起作用,一无所获

标签: javascript regex string pattern-matching match


【解决方案1】:

我认为您正在使用的功能可能是矫枉过正。您只需将所有出现的通配符替换为等价的正则表达式,并匹配输入的开头和结尾。这应该有效:

const fnmatch = (glob, input) => {

  const matcher = glob
                  .replace(/\*/g, '.*')
                  .replace(/\?/g, '.'); // Replace wild cards with regular expression equivalents
  const r = new RegExp(`^${ matcher }$`); // Match beginning and end of input using ^ and $
  
  return r.test(input);
 }

console.log(fnmatch('*.js', 'myfile.js')); // true
console.log(fnmatch('*.js', 'myfile.json')); // false
console.log(fnmatch('?yfile.js', 'myfile.js')); //true

【讨论】:

  • 我希望 cmets 可以更短,因为我想评论说“干得好”,但这太短了。所以这是我更长的评论,说“干得好”:)
  • 谢谢,好的,很好但是这不起作用:fnmatch('?yfile.*', 'myfile.js');是否可以添加'?通配符?原函数支持这个。
  • 这将是链接另一个替换的问题,例如.replace(/\?/g, '.')
  • 太棒了,感谢 amzing 的帮助。现在好多了。谢谢。
  • 不客气!我已更新我的答案以包含 ? 通配符
猜你喜欢
  • 1970-01-01
  • 2011-08-10
  • 2012-03-13
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多