城市名称的正则表达式 [英] Regular Expressions for City name

查看:88
本文介绍了城市名称的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式来验证城市文本框,城市文本框字段只接受字母、空格和破折号(-).

I need a regular Expression for Validating City textBox, the city textbox field accepts only Letters, spaces and dashes(-).

推荐答案

这可以是任意复杂的,这取决于您需要匹配的精确程度以及您愿意允许的变化.

This can be arbitrarily complex, depending on how precise you need the match to be, and the variation you're willing to allow.

^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$ 这样相当简单的东西应该可以工作.

Something fairly simple like ^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$ should work.

警告:这与慕尼黑等城市不匹配,但在这里您基本上需要使用表达式的 [a-zA-Z] 部分,并定义允许的字符你的特殊情况.

warning: This does not match cities like München, etc, but here you basically need to work with the [a-zA-Z] part of the expression, and define what characters are allowed for your particular case.

请记住,它也允许像 San----Francisco 这样的东西,或者有几个空格.

Keep in mind that it also allows for something like San----Francisco, or having several spaces.

翻译成类似的东西:1 个或多个字母,后跟一个块:0 个或多个空格或破折号和更多字母,最后一个块可以出现 0 次或多次.

Translates to something like: 1 or more letters, followed by a block of: 0 or more spaces or dashes and more letters, this last block can occur 0 or more times.

里面有一些奇怪的东西:?: 位.如果您不熟悉正则表达式,它可能会令人困惑,但这只是说明括号之间的正则表达式不是捕获组(我不想捕获它匹配的部分以供以后重用),因此括号仅用于对表达式进行分组(而不用于捕获匹配项).

Weird stuff in there: the ?: bit. If you're not familiarized with regexes, it might be confusing, but that simply states that the piece of regex between parenthesis, is not a capturing group (I don't want to capture the part it matches to reuse later), so the parenthesis are only used as to group the expression (and not to capture the match).

"New York" // passes

"San-Francisco" // passes

"San Fran Cisco" // passes (sorry, needed an example with three tokens)

"Chicago" // passes

"  Chicago" // doesn't pass, starts with spaces

"San-" // doesn't pass, ends with a dash

这篇关于城市名称的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆