Reputation: 3419
I am creating a regular expression to validate a city field. With the following code, I only can validate a City field with one space:
Pattern pattern_ = Pattern.compile("^[a-zA-Z]+(?:[\\s-][a-zA-Z]+)*$");
Any advice about how to improve my regular expression to validate city fields with more than one space?
Well, finally I am using this regexp:
Pattern pattern_ = Pattern.compile("^[a-zA-Z]+(?:(?:\\s+|-)[a-zA-Z]+)*$");
But now I am having a problem with accents How do I add accents to my city field?
Upvotes: 0
Views: 8274
Reputation: 149108
Well, the easiest way would be this:
^[a-zA-Z\s-]+$
Or if you prefer, you can do this, which will ensure that the string doesn't start or end with a whitespace or hyphen:
^[a-zA-Z][a-zA-Z\s-]+[a-zA-Z]$
Of course, don't forget to escape the \
in Java:
Pattern pattern_ = Pattern.compile("^[a-zA-Z][a-zA-Z\\s-]+[a-zA-Z]$");
Upvotes: 2
Reputation: 89649
use an alternation instead of a character class:
Pattern pattern_ = Pattern.compile("^[a-zA-Z]+(?:(?:\\s+|-)[a-zA-Z]+)*$");
Upvotes: 5