0

我需要构建一个只允许字母和连字符的正则表达式,但它需要连字符。

我试过了:

  • ^[a-z]+[a-z\-]+[a-z]+$(没有连字符的匹配通过)
  • ([A-Za-z\-]+)(没有连字符的匹配也通过)
  • [a-zA-Z][\-]+(它没有工作)

有人可以写给我吗?

提前致谢。

4

4 回答 4

1

其他答案都不需要连字符。尝试[a-zA-Z-]*[-][a-zA-Z-]*

于 2012-09-17T02:58:10.000 回答
0

You need a look ahead:

^(?=.*-)[a-zA-Z-]+$

That little expression (?=.*-) is a "look ahead", which is a non-consuming assertion that .*- appears somewhere ahead, which means "there needs to be hyphen in the input"

Also, when put first or last the hyphen is a literal hyphen that doesn't need escaping, otherwise a hyphen denotes a range.

于 2012-09-17T02:54:56.677 回答
0

我不确定您的问题是否列出了所有要求。从你所说的一切开始,这种模式将允许字母和连字符,并且至少需要 1 个连字符。

[a-zA-Z-]*-[a-zA-Z-]*

这允许字符串“-”可以吗?

于 2012-09-17T03:06:43.393 回答
-1

你没有说是哪种语言,所以这里是 Javascript:

Code-> "te-st".match(/[A-Za-z-]+/)
Result -> ["te-st"]
于 2012-09-17T02:56:06.620 回答