更精确的通配符正则表达式

时间:2018-09-21 18:16:58

标签: javascript regex string pattern-matching match

我制定了一个通配符过滤器例程,以使用通配符来匹配文件名。例如:1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <f26106f7890945d7922088b4caacae4a>:0 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x0003e] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x00028] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x00008] in <43dbbdc147f2482093d8409abb04c233>:0 at System.Runtime.CompilerServices.TaskAwaiter给我目录中的所有js文件。

但是,当目录中有一个*.js文件时,我也会得到这些文件。我知道为什么,但是那不是我想要的。

我使用此(从网站中挑选)wildcardStringToRegexp函数来构建RegExp(因为我不擅长此事):

.json

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更精确吗?

1 个答案:

答案 0 :(得分:2)

我认为您使用的功能可能会过大。您只需要用等价的正则表达式替换所有出现的通配符,并匹配输入的开头和结尾即可。这应该起作用:

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