Reputation: 867
I use this regex to check the field City:
"[a-zA-Z]+[[ '-]?[a-zA-Z]+]*"
but it works good also for name such as:
Sant'''''Angelo
Andria---------Barletta
I would like that the special characters " ","'" and "-" between the words must be one and only one. For example:
Sant'Angelo-Dei Lombardi
it must be good, but not:
Sant'''Angelo---Dei Lombardi
Upvotes: 0
Views: 5331
Reputation: 2892
Use this code to validate city:
public static boolean validateCity( String city )
{
return city.matches( "([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)" );
}
Upvotes: 0
Reputation: 44259
You want to use parentheses for the repetition:
[a-zA-Z]+(?:[ '-][a-zA-Z]+)*
What you tried ([[ '-]?[a-zA-Z]+]
) means a character class, containing [ '-]
, ?
, [a-zA-Z]
and +
, effectively being equivalent with [a-zA-Z?+ '-]
. Subpatterns on the other had are delimited with (
and )
, and the ?:
makes it non-capturing which is a slight optimization.
Upvotes: 4