对于正常的注册名称,可以是{-1}}和a-zA-Z
的1-n字符,例如
-
但larry-cai, larrycai, larry-c-cai, l,
不能是第一个和最后一个字符,例如
-
我的想法就像
-larry, larry-
但如果我的正则表达式
,则长度应为2应该很简单,但不要怎么做
,那就太好了答案 0 :(得分:6)
您没有指定您正在使用的正则表达式引擎。一种方法是(如果您的引擎支持lookaround):
^(?!-)[A-Za-z-]+(?<!-)$
<强>解释强>
^ # Start of string
(?!-) # Assert that the first character isn't a dash
[A-Za-z-]+ # Match one or more "allowed" characters
(?<!-) # Assert that the previous character isn't a dash...
$ # ...at the end of the string.
如果lookbehind不可用(例如在JavaScript中):
^(?!-)[A-Za-z-]*[A-Za-z]$
<强>解释强>
^ # Start of string
(?!-) # Assert that the first character isn't a dash
[A-Za-z-]* # Match zero or more "allowed" characters
[A-Za-z] # Match exactly one "allowed" character except dash
$ # End of string
答案 1 :(得分:4)
这应该这样做:
^[a-zA-Z]+(-[a-zA-Z]+)*$
这样,在开头(^[a-zA-Z]+
)需要有一个或多个字母字符。如果跟随-
,则需要至少跟一个字母字符(-[a-zA-Z]+
)。该模式可以重复任意一次,直到到达字符串的末尾。
答案 2 :(得分:4)
一个简单的答案是:
^(([a-zA-Z])|([a-zA-Z][a-zA-Z-]*[a-zA-Z]))$
匹配长度为1的字符串和字符a-zA-Z,或者匹配原始表达式的改进版本,这对于长度大于1的字符串很合适。
改进归功于Tim和ridgerunner(见评论)。
答案 3 :(得分:1)
试试这个:
^[a-zA-Z]+([-]*[a-zA-Z])*$
答案 4 :(得分:0)
不确定哪个懒群优先。
^[a-zA-Z][a-zA-Z-]*?[a-zA-Z]?$
答案 5 :(得分:0)
也许这个?
^[^-]\S*[^-]$|^[^-]{1}$