I need regexp to remove all not digits and not dash ('-'). new RegExp('[^0-9-]')
seems works but new RegExp('[\\D-]')
remove dash also. Why is this different?
I need regexp to remove all not digits and not dash ('-'). new RegExp('[^0-9-]')
seems works but new RegExp('[\\D-]')
remove dash also. Why is this different?
-
2
Because
[\D-]
is 'match any non-digit symbol OR dash', while[^0-9-]
is 'match any symbol that's not digit or dash'. – raina77ow Commented Feb 5, 2013 at 20:40 -
1
[\D-]
is equivalent to[\D]
, as the-
is already matched by\D
. – Blender Commented Feb 5, 2013 at 20:41 -
3
Guys, it's JS: clearly
\\D
is how it's written in the string literal, not the regex one (it wouldn't match digits at all otherwise). The difference is worth to be mentioned, though. ) – raina77ow Commented Feb 5, 2013 at 20:46 -
@raina77ow: I don't normally use
new RegExp
, I use regex literals, so I didn't think of that. – gen_Eric Commented Feb 5, 2013 at 20:53
5 Answers
Reset to default 13[^0-9-]
is "anything that is NOT a digit, or is NOT a dash
[\D-]
is "anythign that is NOT a digit, or IS a dash
the ^
inverts the entire []
character class, so on your \D
version, there's no inversion, so a -
is a legitimate match.
Because there is no negation in front of the dash in the second one. The \D
(there should only be one backslash really) means 'all not-digits', the dash means a dash.
Because you have interpreted the meaning of your second regex wrong.
The ^
at the beginning of the character class [^0-9-]
matches all characters specified in it, specifically anything thats not 0-9
and not -
. Whereas [\D-]
matches anything thats not a digit and is a -
.
When you use the ^
in a character class ([]
), it means "NOT anything in this class". \D
is just a special sequence that means "anything that's not a digit".
So:
[^0-9-]
matches anything that isn't a digit or a -
.
[\D-]
means "any non-digit character (or a -
, which is already a non-digit). There is no need for the []
here, this is the same as just \D
by itself.
\D
is simple shorthand for ^0-9