正则表达式:要么只有数字或字母数字与' - '和'_'允许但不是数字' - '和' - '

时间:2017-12-22 13:44:59

标签: javascript regex pattern-matching

我遇到了模式匹配问题,我正在尝试生成一种模式,该模式只接受数字或字母数字,其中包含“-”和“_”,但不允许使用“- }'和'-'允许,且不应允许“-”和“_”。

我尝试了下面的一个有点工作但完全正常工作。

^[a-zA-Z0-9][a-zA-Z0-9-_]+$

我正在尝试匹配以下案例:

abcd = OK
as123 = Ok
as_as = Ok
as_12 = Ok
as-as = ok
12as = Ok
12_1as = Ok
123_12 = not Ok
12-12 = not Ok
1234 = ok
-- = not ok
__ = not ok

提前致谢

2 个答案:

答案 0 :(得分:1)

这就是工作:



^           : begining of string
  (?!       : negative lookahead, make sure we don't have
    \d+     : 1 or more digits
    [-_]    : - or _
    \d+     : 1 or more digits
    $       : end of string
  )         : end lookahead
  [a-z0-]+  : 1 or more alphanumeric character
  [-_]?     : optional - or _
  [a-z0-]+  : 1 or more alphanumeric character
$           : end of string




<强>解释

0.05 <= diff < .10

答案 1 :(得分:0)

你正在寻找这样的正则表达式,它可以从负面的前瞻中获益:

^(?!\d*(?:[-_]+\d*)*$)[\w-]+$

Live demo