1

I am validating a city field and I would like to accept spaces between words, for example "San Francisco". Right now I only can validate cities of a single word.

How could I improve my code?

public static boolean verifyCity (Context context, String _string) {

    Pattern pattern_ = Pattern.compile("[a-zA-Z]+[\\s]+");

    Matcher matcher = pattern_.matcher(_string);
    boolean matchFound = matcher.matches();

    if (matchFound) return true;
    else            return false;
   }
HamZa
  • 14,671
  • 11
  • 54
  • 75
MarcForn
  • 3,321
  • 7
  • 25
  • 39
  • 1
    Related - http://stackoverflow.com/questions/11757013/regular-expressions-for-city-name – AJak Aug 09 '13 at 21:15
  • Really grateful. I couldn't find that post. – MarcForn Aug 09 '13 at 21:23
  • Make sure you can handle "Salt Lake City". And "Winston-Salem". And I'm sure there are city names with single-quote marks in them, but I can't think of any big ones right now--something like "Tom's Corners". Oh, yeah, California has "29 Palms" but I think it's usually spelled Twentynine Palms. How about "St. Paul"? – ajb Aug 09 '13 at 21:32
  • Aha, I thought of one: Coeur d'Alene, Idaho. – ajb Aug 09 '13 at 21:39

1 Answers1

1

Why not just allow spaces in the range

Pattern pattern_ = Pattern.compile("[A-Z][a-zA-Z\\s]*[A-Za-z]");

The other ranges are to avoid spaces at the beginning or end.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134