views:

66

answers:

3

I want to sort out specific files depending on their names, i want a regex that returns true for file names like : 01.mp4, 99.avi, 05.mpg.

the file extensions must match exactly to the ones that i want and the filename must start with characters which can not be longer than 2 characters. the first part is done but the file extensions aren't working. need some help the regex that I have is

/^[0-9]{1,2}\.[mp4|mpg|avi]*/

but it also returns true for 01.4mp4, 01.4mp4m.

+6  A: 

Try this:

/^[0-9]{1,2}\.(?:mp4|mpg|avi)$/
Kerry
can you tell me what does ?: do here, i what i think is that is somehow limits the characters of extension
Umair
To explain: the square brackets, `[]`, denote a character class; `[abc]` means "match either `a` or `b` or `c`", and `[a-z]` means "match any character between `a` and `z`". Thus, `[mp4|mpg|avi]` matches *any of those characters*, the order being irrelevant. Parentheses, `()`, group regular expressions, which is what you want to do. The `?:` bit tells the regex engine not to allocate a capturing group for that set of parentheses, otherwise it would be accessible with `$1`.
Antal S-Z
oh alright, if I am not wrong then this simply means that () match exactly whats given, while having ?: or not wont matter that much
Umair
Yes, in a way; you get a slight performance benefit if you use `(?:...)`, and it might help later on in regexes where you have several capturing groups and several non-capturing groups to keep the numbering of backreferences simple. Apart from that, `(...)` will match exactly the same as `(?:...)`.
Tim Pietzcker
A: 
/^[0-9]{1,2}\.[mp4|mpg|avi]?/
turbod
That would make the extension optional (but non repeating), but it wouldn't solve the original problem.
Thorarin
How is it different from OP's regex and how does it solve the problem - you're confused between parenthetic groups `()` and character class `[]`
Amarghosh
A: 

I played a bit with my original regex and came up with this

/^[0-9]{1,2}\.[mp4|mpg|avi]{3}$/

and this works like a charm :)

Umair
Try `11.mmm`. _
KennyTM
thak you for pointing this out Kenny, it didnt work indeed
Umair