0

Here's is my javascript regex for a city name and it's handling almost all cases except this.

^[a-zA-Z]+[\. - ']?(?:[\s-][a-zA-Z]+)*$

(Should pass)

  • Coeur d'Alene
  • San Tan Valley
  • St. Thomas
  • St. Thomas-Vincent
  • St. Thomas Vincent
  • St Thomas-Vincent
  • St-Thomas
  • anaconda-deer lodge county

(Should Fail)

  • San. Tan. Valley
  • St.. Thomas
  • St.. Thomas--Vincent
  • St.- Thomas -Vincent
  • St--Thomas
4

3 回答 3

1

这匹配第一个列表中的所有名称,而不是第二个列表中的名称:

/^[a-zA-Z]+(?:\.(?!-))?(?:[\s-](?:[a-z]+')?[a-zA-Z]+)*$/

多行解释:

^[a-zA-Z]+     # begins with a word
(?:\.(?!-))?   # maybe a dot but not followed by a dash
(?:
 [\s-]         # whitespace or dash
 (?:[a-z]+\')? # maybe a lowercase-word and an apostrophe
 [a-zA-Z]+     # word
)*$            # repeated to the end

要在任何地方允许点,但不允许两个点,请使用以下命令:

/^(?!.*?\..*?\.)[a-zA-Z]+(?:(?:\.\s?|\s|-)(?:[a-z]+')?[a-zA-Z]+)*$/

^(?!.*?\..*?\.) # does not contain two dots
[a-zA-Z]+       # a word
(?:
 (?:\.\s?|\s|-) # delimiter: dot with maybe whitespace, whitespace or dash
 (?:[a-z]+\')?  # maybe a lowercase-word and an apostrophe
 [a-zA-Z]+      # word
)*$             # repeated to the end
于 2013-01-28T15:39:40.223 回答
0

试试这个正则表达式:

^(?:[a-zA-Z]+(?:[.'\-,])?\s?)+$

这确实匹配:

Coeur d'Alene
San Tan Valley
St. Thomas
St. Thomas-Vincent
St. Thomas Vincent
St Thomas-Vincent
St-Thomas
蟒蛇-鹿小屋县
Monte St.Thomas
San。谭。谷
华盛顿特区

但不匹配:

圣托马斯
圣托马斯--文森特圣-托马斯-文
森特
圣--托马斯

(我允许它匹配San. Tan. Valley,因为那里可能有一个带有 2 个句点的城市名称。)

正则表达式的工作原理:

# ^         - Match the line start.
# (?:       - Start a non-catching group
# [a-zA-Z]+ - That starts with 1 or more letters.
# [.'\-,]?  - Followed by one period, apostrophe dash, or comma. (optional)
# \s?       - Followed by a space (optional)
# )+        - End of the group, match at least one or more of the previous group.
# $         - Match the end of the line
于 2013-01-29T07:50:50.160 回答
0

我认为以下正则表达式符合您的要求:

^([Ss]t\. |[a-zA-Z ]|\['-](?:[^-']))+$

另一方面,您可能会质疑使用正则表达式来做到这一点的想法......无论您的正则表达式有多复杂,总会有一些傻瓜找到一个新的不想要的模式来匹配......

通常当您需要有效的城市名称时,最好使用一些地理编码 API,例如google geocoding API

于 2013-01-28T15:38:02.523 回答