正则表达式连续禁止超过1个破折号

com*_*tta 9 regex

  1. 我如何禁止--(连续超过1次)?例如ab--c
  2. - 在词语的后面不允许,例如 abc-
  3. - 在单词的开头不允许,例如 -abc

^[A-Za-z0-9-]+$ 是我到目前为止.

Bri*_*hle 27

^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$

使用此正则表达式,连字符仅在组内匹配.此连字符的[A-Za-z0-9]+每一侧都有子表达式.因为此子表达式匹配一个或多个字母数字字符,所以连字符不能在开头,结尾或另一个连字符旁边匹配.

  • @Sachin:据我了解OP,这正是他想要的.不过,他可能更明确. (4认同)
  • @Brian:你是对的.它确实比前瞻更优雅(也更快).+1 :-) (2认同)

Tim*_*ker 21

^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$
Run Code Online (Sandbox Code Playgroud)

说明:

^             # Anchor at start of string
(?!-)         # Assert that the first character isn't a -
(?!.*--)      # Assert that there are no -- present anywhere
[A-Za-z0-9-]+ # Match one or more allowed characters
(?<!-)        # Assert that the last one isn't a -
$             # Anchor at end of string
Run Code Online (Sandbox Code Playgroud)