1

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.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
jeff
  • 1,169
  • 1
  • 19
  • 44
  • What language/environment will you be running this pattern in? Can you offer a few sample inputs and your expected result for each? Please post your language specific regex implementation. – mickmackusa Jul 03 '17 at 14:31
  • javascript, filename blabla.js should match, blabla-test.js should not match. everything with .scss and .jsx should match. used for webpack config – jeff Jul 03 '17 at 14:39

3 Answers3

2

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'));
})
Piyush
  • 1,162
  • 9
  • 17
  • thx this works, but not perfectly: the exact antipattern should be "*-test.js", so no space other characters between "test" and ".js" and the minus is a part of the pattern https://regex101.com/r/upQVte/4 – jeff Jul 03 '17 at 15:40
  • @jeff Sorry about that. Updated my answer just in case. – Piyush Jul 03 '17 at 15:46
  • thanks, "sadadf-testddd.js" is still a wrong negative – jeff Jul 03 '17 at 15:54
1

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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

Try this one:

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

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

Adam
  • 4,985
  • 2
  • 29
  • 61