skip to Main Content

For example, I want to check if a file has only one extension. I tried to use the groups, but they don’t allow me to verify that they appear only once (I didn’t find out how to do it)

Here is an example used:

.(js|jsx)$

For example, if js and jsx are allowed:

test.js -> should match
test.jsx -> should match
test.ts -> should not match
test.js.jsx -> should not match

Any string with .js.jsx, .jsx.jsx, .jsx.js or .js.js at the end are not allowed.

2

Answers


  1. .w+.w+ this regex expression matches files with more than one extension. However, it may be necessary to do some string operations first.

    Login or Signup to reply.
  2. Only one extension, means no dot before the extension, use [^.] to specify any chars but not dot. The full regular expression:

    /^[^.]+.(js|jsx)$/
    

    But if you want to check if a file has only one allowed extension, you can use a global match:

    /.(js|jsx)b/g
    

    Here is a example:

    const REGEXP1 = /.(js|jsx)b/g;
    const REGEXP2 = /^[^.]+.(js|jsx)$/;
    
    const files = [
      'test.js',
      'test.jsx',
      'test.ts',
      'test.js.jsx',
      'test.ts.jsx',
    ];
    
    console.log('REGEXP1');
    
    files.forEach((file) => {
      const match = file.match(REGEXP1);
      console.log(!!(match && match.length === 1));
    });
    
    console.log('REGEXP2');
    
    files.forEach((file) => {
      const match = file.match(REGEXP2);
      console.log(!!match);
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search