1

I am using bean validation in a spring mvc application. I have a form with a text field which should accept only alphabetics and the hyphen (it is optional but if the user put it we should accept it). I've try this @Pattern( regexp = "\\p{Alpha}*" ) but only letters are accepted. Does someone have an idea?

Many thanks

akuma8
  • 2,822
  • 1
  • 25
  • 55

1 Answers1

1

To match zero or more letters or hyphens use

@Pattern( regexp = "[\\p{Alpha}-]*" )

The [...] is a character class that matches 1 char defined inside the class. By adding both \\p{Alpha} and - inside we can match either letters or hyphens, and due to the * quantifier there can be 0 or more of such characters.

If you add more chars in to the class later, consider escaping the hyphen, or remember to always keep it at the end of the class.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Thanks for these explanations but why there isn't any seperation between `\\p{Alpha}` and `-`? – akuma8 Oct 26 '16 at 15:29
  • Because the relations between them inside a positive character class is OR. `[abc]` means to match either `a`, or `b`, or `c`, only one occurrence. See [*Character Classes or Character Sets*](http://www.regular-expressions.info/charclass.html). – Wiktor Stribiżew Oct 26 '16 at 15:31
  • Thanks for this explanation, you just teach me how to create my own Regexp and save me time because I lose valuable time searching Regexp on the internet. Is there any other basic rules should I know?^^ – akuma8 Oct 26 '16 at 15:39
  • I can only suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). . Also, [rexegg.com](http://rexegg.com) is worth having a look at. – Wiktor Stribiżew Oct 26 '16 at 15:43