jeff
jeff

Reputation: 1197

Regex to exclude a pattern in filename

My current pattern is:

/\.(scss|js|jsx)$/  

I want to exclude files that end with "-test.js"

I've tried:

/(?!-test)\.(scss|js|jsx)$/

but it's not working.

Upvotes: 1

Views: 2308

Answers (3)

mickmackusa
mickmackusa

Reputation: 47854

js|jsx can be refined/sped-up by using: jsx?.
scss can be sped-up by using scs{2}.
Putting shorter "alternatives" before longer ones will improve speed. (jsx?|scs{2})

Patterns:

/^(.(?!-test\.js$))+\.(jsx?|scs{2})$/

or in nearly half the steps, due to removed capture group:

/^(?!.*-test\.js$).*\.(jsx?|scs{2})$/

Demo

Test cases:

a-test.js      #fail
b-test.scss    #pass 
c-test.jsx     #pass
d.js           #pass
e.scss         #pass
f.jsx          #pass
g-testg.js     #pass
h-testh.scss   #pass
i-testi.jsx    #pass

Upvotes: 1

Piyush
Piyush

Reputation: 1162

As JS does not support lookbehind, you can do ^(?!.*-test\.js$).*\.(js|scss|jsx)$ as a workaround.

Regex Demo

var testFiles = ['p-test.js',
  'q-test.scss',
  'r-test.jsx',
  'p.js',
  'q.scss',
  'r.jsx',
  'sadadf-testddd.js'
];
var myRegexp = /^(?!.*-test\.js$).*\.(js|scss|jsx)$/g;
testFiles.forEach(function(file) {
  var match = file.match(myRegexp)
  console.log(file + " : " + (match ? 'matches' : 'does not match'));
})

Upvotes: 2

Adam
Adam

Reputation: 5233

Try this one:

/^([a-z0-9-_](?!-test\.))+\.(scss|js|jsx)$/

None of the characters of the filename should be followed by -test..

Upvotes: 0

Related Questions