tom
tom

Reputation: 5001

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

Upvotes: 2

Views: 2278

Answers (4)

Faisal Feroz
Faisal Feroz

Reputation: 12785

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

Upvotes: 2

codaddict
codaddict

Reputation: 455400

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 *

Upvotes: 7

Ruel
Ruel

Reputation: 15780

If you allow uppercase use this:

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

otherwise:

^[a-z-]+?$

Upvotes: 2

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94284

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.

Upvotes: 2

Related Questions