I wrote a script that uses wildcards to filter filenames. For example, using `*.js` will give me all the JavaScript files in a directory.
However, I encountered an issue where it also includes `.json` files in the results, which is not what I intended.
To create the RegExp pattern, I used the `wildcardStringToRegexp` function that I found on a website because regex isn't my strong suit:
function wildcardStringToRegexp( s )
{
if( isValidString( s ))
{ return false; }
function preg_quote(str, delimiter)
{
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;
}
For instance:
fnmatch( '*.js', 'myfile.js' ) returns 1
fnmatch( '*.js', 'myfile.json' ) returns 1 , but this is not desired
How can I modify the wildcardStringToRegexp
() function or make other changes so that fnmatch( '*.js', 'myfile.json' )
is no longer valid and the filtering becomes more accurate?