在javascript中我有
var regex = /^\d+$/;
仅接受数字。如何重新制作它以接受数字和字符' - '
答案 0 :(得分:4)
您可以使用character class:
var regex = /^[\d-]+$/;
但是,这也会允许----
之类的匹配。如果您只想允许输入123-456-789
但不允许-123
或123-
或123--456
,那么您可以使用类似
var regex = /^\d+(?:-\d+)*$/;
<强>说明:强>
^ # Start of string.
\d+ # Match a number.
(?: # Start of a non-capturing group that matches...
- # a hyphen,
\d+ # followed by a number
)* # ...any number of times, including zero.
$ # End of string