views:

93

answers:

4
+2  Q: 

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

+6  A: 

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 *

codaddict
Now here's an explanation that the OP will probably understand. Nice (+1)
seanizer
Thank you very much, i find regex really difficult and i couldnt think of any other approach to solving this manually :/ (i guess inexperience is the problem there ;) )
tom
@tom don't let that get you down. Regular Expressions are awful beasts. It takes some programmers years to understand them. You'll figure it out eventually if you try. Here is a Java Online Regex Tester: http://www.fileformat.info/tool/regex.htm . You might want to play around with that, it might help you understand things better
seanizer
+1  A: 

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.

Daniel Vandersluis
I think hyphen (-) should be escaped.
Faisal Feroz
@Faisal the hyphen does not need to be escaped in a character class if it is the last character.
Daniel Vandersluis
Can the downvoters please explain?
Daniel Vandersluis
Can't find anything wrong with this (+1)
seanizer
+2  A: 

If you allow uppercase use this:

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

otherwise:

^[a-z-]+?$

Ruel
+3  A: 

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

Faisal Feroz
+1 for escaping hyphen.
Tingu
@Tingu it is not necessary to escape a hyphen in a character class if it is the last character in it. Take a look at the section called "Metacharacters Inside Character Classes" in [this article](http://www.regular-expressions.info/charclass.html)
Daniel Vandersluis
If string matches this regex, then its fine - ain't it? Btw, hyphen need not be escaped when it is the first/last character in a character class @Tingu
Amarghosh
@Amarghosh thanks for pointing out. Fixed the answer.
Faisal Feroz