1

Could someone please help me with RegEx?

  1. It should include all JavaScript files, except foo.[contenthash].js and bar.[contenthash].js.

  2. It should only skip files where the foo or bar appears at the beginning of the file name.

  3. It should not skip partial file name i.e. fo.[contenthash].js (please see missing o in foo) should not be skipped.

Could someone please help? Thanks in advance.

morgan121
  • 1,989
  • 1
  • 12
  • 27

2 Answers2

0
import re

files = ["index.js", "index.html", "main.js", "foo.js", "bar.js", "foo.something.js", "foo.something1.js", "bar.something.js", "bar.something1.js", "fo.something.js"]

patternjs = r"^.+\.js$"
patternfoo = r"^fo.+\.js$"
patternbar = r"^ba.+\.js$"
patternexcludefoo = r"^foo\.\w+\.js$"
patternexcludebar = r"^bar\.\w+\.js$"

for file in files:
    resultfoo = re.match(patternfoo, file)
    resultbar = re.match(patternbar, file)
    resultjs = re.match(patternjs, file)
    resultexcludefoo = re.match(patternexcludefoo, file)
    resultexcludebar = re.match(patternexcludebar, file)

    if resultfoo or resultbar:
        print(file + " is js file either of foo type or bar type")

    if resultjs:
        print(file + " is js file")

    if resultexcludefoo or resultexcludebar:
        print(file + " is to be excluded")

As you got the strings, you can manipulate the files accordingly

PS: The code maybe somewhat not upto the mark as I had learned RegEx only 2 days ago. This was the code that I came upto. Didn't checked for JavaScript but these patterns may work as well in JavaScript ( It doesn't support lookbehind and I haven't used it in this code)

Mann
  • 81
  • 1
  • 7
  • Thanks for your help. I'm hoping to find a new line RegEx solution like the following: /^(?![^client$|^vendor$]\/.*\.js)/.test('client.7eb29947b4b76c5ae5589a297482c574.js'); Of course, it's working right now, but that's why I am seeking help. – undefined999 Feb 08 '19 at 04:34
  • Didn't get you. Can you please explain further – Mann Feb 08 '19 at 04:39
  • The solution should be in `JavaScript`, not in `Python`, I suppose. – Jan Feb 08 '19 at 06:33
  • 1
    @Mann, thanks for your help. Jan's solution is more suitable for my requirement. Thanks and good luck. – undefined999 Feb 08 '19 at 21:10
0

You could use a negative lookahead with anchors right at the start:

^(?!foo|bar).*\.js$


In JavaScript this could be:

let files = ['test.12345.js', 'foo.12345.js', 'bar.12345.js'];

let regex = /^(?!foo|bar).*\.js$/

files.forEach(function(file) {
    console.log(regex.test(file));
});

See an additional demo on regex101.com.
Jan
  • 38,539
  • 8
  • 41
  • 69