Increased accuracy in wildcard regexp usage

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?

Answer №1

In my opinion, it seems like the function you are utilizing may be a bit excessive. Instead of that, all you really need to do is substitute all instances of wildcards with their regex equivalents and ensure that you match both the beginning and end of the input. The modified code should look something like this:

const fnmatch = (glob, input) => {

  const matcher = glob
                  .replace(/\*/g, '.*')
                  .replace(/\?/g, '.'); // Converting wildcards to regex values
  const r = new RegExp(`^${ matcher }$`); // Matching 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The useEffect() method used without any cleanup function

It is mentioned that, "Every time our component renders, the effect is triggered, resulting in another event listener being added. With repeated clicks and re-renders, numerous event listeners are attached to the DOM! It is crucial to clean up after oursel ...

Troubleshoot: Trouble with selecting the clicked item in AngularJS when using ng-repeat

Is there a way to only delete the selected item from my ng-repeat list instead of deleting all items at once? I can currently delete all items using ng-repeat, but I want to be able to delete just the clicked item. How can I achieve this? https://i.stack. ...

What is the best way to completely eliminate a many-to-many relationship with a custom property?

I have encountered a situation where I am utilizing an entity setup similar to the one explained in this resource. The problem arises when I try to remove entries from post.postToCategories. Instead of deleting the entire row, TypeORM sets one side of the ...

Quickly Alter Background Image when Hovered Over

I am looking to enhance my website by having the background image change on mouseover of an object, with the replacement image only showing for a quick moment before returning to the original. Additionally, I want to incorporate a short sound file into the ...

What is the best approach to transform an HTML textarea value into JSON format?

Client .. inserting some content into a form <textarea name="data"></textarea> After typing the following data into the textarea: {title: 'Hello one!', author: 'someone'} {title: 'Hello two!', author: 'mygf ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

Getting numerous MongoDB records with identical attributes by means of Express

I am attempting to retrieve all MongoDB entries associated with a specific username using Express. Here is the code I have written: transcriptRepository.getTranscriptByUsername = (username) => { return Transcript.find({ username }) .then( tran ...

Generate a new structured Record / Object using the keys from an existing one using code

Within my TypeScript program, I have defined two base types (Player, State) and a few nested Record types that serve as mappings. Using a typed function, an instance of one of these records is created based on an existing instance of the nested record. t ...

The alpha value returned by gl.readPixels in Three.js will consistently be 255

Is there a way to retrieve pixel values from a threejs application? const gl = renderer.context; const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4); // read image data from gl gl.readPixels(0, 0, gl.drawingBufferWidth ...

What is the best way to keep an image centered in the nav-bar as it decreases in size?

As I work on building a website using a template (https://github.com/learning-zone/web-templates/tree/master/victory-school-free-html5-bootstrap-template), I encountered an issue with the navigation bar. The original design appears like this: Before shrin ...

Dealing with checkbox's checked and unchecked events using JavaScript

I am facing a challenge with a read-only textbox used for date input from a JavaScript date picker. Additionally, I have a gridview with checkboxes in the item template. My goal is to have the corresponding date filled in the textbox when a user clicks o ...

Positioning Multi-level Drop Down Div in Javascript - How to do it efficiently?

I'm currently working on a horizontal menu using CSS and JavaScript with multiple levels. I've implemented a toggle function to show the submenu container, but it's causing the links below it to be pushed down. Is there a way to make the dis ...

Retrieving data from an XML file using an Ajax request

I am using a native AJAX request to insert node values into HTML divs. However, I have noticed that when I update the XML values and upload them to the server while the website is running, Chrome and IE do not immediately reflect the changes (even after re ...

Error: Encountered an unexpected token F while trying to make a POST request using $http.post and Restangular

In our current project, we are utilizing Angular and making API calls with Restangular. Recently, I encountered an error while trying to do a POST request to a specific endpoint. The POST call looked like this: Restangular.one('aaa').post(&apos ...

Python program to remove overlapping characters from two strings

Suppose you have two strings, stringA and stringB (where len(stringA) is greater than len(stringB)). How can you remove all characters from stringA that are also present in stringB? It should be assumed that all characters in stringB are present in stringA ...

The functionality of Bootstrap tabs is compromised when used within a modal dialog

I am encountering an issue while using Django and Bootstrap to implement nav-tabs within a modal that is displayed upon clicking a button. The problem lies in the fact that when a tab is clicked, its content does not appear. Below is a basic example: {% ...

Accessing environmental variables from pug template

Currently, I am utilizing pug to generate static HTML for my own customized static site builder. In my package.json file, the only line of Node.js server code present is: "watch-pages": "pug -O options.json -w pages/ --out _static-website/" However, the ...

Contrasting Router.push and location.assign: Exploring the variances between

One thing I've noticed in my React app is that when I use Router.push('/') from `import Router from 'next/router', the page I am navigating to doesn't fully refresh. This causes some loading spinners whose states I want to be ...

Wrap a collection of text lines with a leading indentation of 4 spaces

I am looking to wrap all the lines within a <pre> tag that start with 4 spaces. What have I attempted so far? ^[ ]{4}(.*)(?!=^[ ]{4}) DEMO Input: Here is the code: String name = "Jon"; System.out.println("Hello "+name); output: Hello ...

Enhance User Experience with JQuery Autocomplete for Internet Explorer 8 Using ASMX Web Services

Help Needed! I have been trying to implement a Web Service (ASMX) file on my website. When I access and query the page, I receive the desired results. The problem arises when I attempt to add autocomplete functionality to a textbox in my ASP.NET applicati ...