In the expression [^-0-9.]
, the hyphen character has a special meaning within the square brackets... unless it comes at the very beginning or end of those square brackets. The -
character here means that it accepts a range: in this case, anything between a literal 0
and a literal 9
as in 0-9
.
However, when the hyphen is either first or last, it has nothing to go "from" (or "to"), so it cannot be treated as a "range" and is therefore parsed to be the -
character.
I have found that being slightly more verbose and escaping the hyphen allows a user to place the hyphen anywhere within the square character group block, and not worry that it accidentally be parsed as a "range" indicator: [^\-0-9.]
or [^0-9\-.]
or [^0-9.\-]
What you have above works correctly because of the placement of the hyphen either at the beginning or end, where you do not need to explicitly escape the character, but it may be easier to read (and expand in the future) if you go with an escaped version so you (or other users) know that the hyphen should be used literally as a hyphen character.