paolo2988
paolo2988

Reputation: 867

Regular Expression City Name

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

Answers (2)

Mahesh
Mahesh

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

Martin Ender
Martin Ender

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

Related Questions