最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RegExp: why [^0-9-] != [D-]? - Stack Overflow

programmeradmin3浏览0评论

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?

Share Improve this question edited Feb 5, 2013 at 20:54 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked Feb 5, 2013 at 20:38 korywkakorywka 7,6532 gold badges27 silver badges50 bronze badges 4
  • 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
Add a ment  | 

5 Answers 5

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

发布评论

评论列表(0)

  1. 暂无评论