[regex] Regex - Should hyphens be escaped?

Possible Duplicate:
How to match hyphens with Regular Expression?

Hyphen is a special character in regex, for instance, to select a range, I could do something like:

[0-9A-F]

But outside of square brackets it's just a regular character right? I've tested this on a couple of online regex testers, and hyphens seem to function as a normal character outside of square brackets (or even inside of square brackets if it's not in-between two characters - eg [-g] seems to match - or g) whether it's escaped or not. I couldn't find the answer to this, but I'm wondering whether or not it is conventional to escape hyphens.

Thanks!

This question is related to regex

The answer is


Typically you would always put the hyphen first in the [] match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]


Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.

Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:] or [._:-], to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:], and I wouldn't call that unconventional.