开发者

java string regex

could someone help me开发者_运维技巧 out with a piece of regex please? I want to stop the user entering any charachter other than a-z or a hyphen -

Hope someone can help me.

Thanks


You can use the regex: ^[a-z-]+$

  • ^ : Start anchor
  • $ : End anchor
  • [..] : Char class
  • a-z : any lowercase alphabet
  • - : a literal hyphen. Hyphen is usually a meta char inside char class but if its present as the first or last char of the char class it is treated literally.
  • + : Quantifier for one or more

If you want to allow empty string you can replace + with *


If the string doesn't match ^[a-z-]*$, then a disallowed character was entered. This pattern is anchored so that the entire string is considered, and uses a repeated character class (the star specifies zero or more matches, so an empty string will be accepted) to ensure only allowed characters are used.


If you allow uppercase use this:

^[A-Za-z-]+?$

otherwise:

^[a-z-]+?$


If a string matches this regex ^[a-z\-]*$ then its fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜