2

I'm using Ext.js for filemanager. I'm trying to allow saving only .c and .cpp files. But I cant get both file extensions to work.

Ext.ns('Editor.FileCombo');

Editor.VTypes = Ext.form.field.VTypes;
Ext.apply(Ext.form.field.VTypes, {Expression
    fileNameExp: /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)$/i, // Expression
    fileName: function(val,field){      // Test
        return this.fileNameExp.test(val);
    },
    fileNameText: 'The filename ist not in a valid format!<br />Filename has to end with \'.c\' Or \'.cpp\,<br />Allowed: a-z,A-Z,0-9,_,- <br />Filename <i>main.c</i> is reserved for the compiler.',      // Error QTIP Text
    fileNameMask: /[\w\d-\.]/i          // valid character Mask
});

Tried to modify fileNameExp to this:

fileNameExp: /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)$([a-zA-z]+[\w-]*\.cpp)/i 

But thats not working.. .I look around the Stackoverflow about this topic, but couldn't understand how to archive this. I would be very much appreciated if someone can fix this expression code!

Godhaze
  • 155
  • 3
  • 16
  • 1
    Why not use a separate trivial check [like this](https://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript) - then you can tell you user if the extension is invalid or if its the filename thats the problem whilst keeping your re simpler. – Alex K. Jul 07 '17 at 12:19
  • The `$` is a special character that signals the end of the input. So you need to say "Choose this one **or** this one" like /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)|([a-zA-z]+[\w-]*\.cpp)/i – Secespitus Jul 07 '17 at 12:25
  • if you add what you added after the `$`, it will not be taken in account, because `$` means "end of the string". you cannot search for things after the end. Your problem can be easily solved by a `|` that means "or": `/^((?!main\.c$)([a-zA-z]+[\w-]*\.c)|(?!main\.cpp$)([a-zA-z]+[\w-]*\.cpp))$/i` – Kaddath Jul 07 '17 at 13:00
  • Try `/^(?!main\.c(?:pp)?$)([a-z][\w-]*\.c(?:pp)?)$/i` - it will match a file name that will start with an ASCII letter, then can have 0+ word or hyphen characters, then `.` followed with `c` or `cpp` at the end of the string. You should not use `[A-z]`, [it does not match only letters](http://stackoverflow.com/a/29771926/3832970). – Wiktor Stribiżew Jul 07 '17 at 19:06

1 Answers1

0

I believe this is the RegEx you are looking for: /(?:^(?!main\.)[^\\/]+\.)(?:c|cpp)$/

You can always use this website to test JS RegEx: https://regex101.com/

Remember to select Javascript on the left hand side.

Guilherme Lopes
  • 4,688
  • 1
  • 19
  • 42