用于验证地址的JavaScript正则表达式 [英] JavaScript regex to validate an address

查看:130
本文介绍了用于验证地址的JavaScript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式验证JavaScript中的居住地址,但我对正则表达式了解不多,我尝试过建立自己的正则表达式( / ^ [a-zA-Z] \\\](\d)?$ / )但它似乎无法正常工作。

I would like to validate residence address in the JavaScript using regex, but I dont know much about the regex, what I have tried is to build my own regex (/^[a-zA-Z\s](\d)?$/) but it doesn't seem to work properly.

我想达到的目标是允许字母,空格和至少一个数字(这是必需的),也应该有可能插入斜杠 / ,但它不应该是必需的。

What I want to achieve is to allow letters, spaces and at least one digit (thats required) and also there should be a possibility to insert the slash / but it shouldnt be required.

任何人都可以帮我吗?

推荐答案

我会帮你的但是当你习惯了正则表达式时,你会发现自己变得更加具体。首先,让我们检查你的正则表达式:

I'll get you started, but you'll find yourself becoming more specific as you get accustomed to regular expressions. First, let's examine your regex:

/^[a-zA-Z\s](\d)?$/

这里需要注意的是,这个正则表达式最多只能匹配两个 - 字符串!字符类 [...] 匹配单个字符:在您的情况下,字母和空格。你需要将它与所谓的量词结合起来,例如 * 意思是零或更多, + 表示一个或多个,表示零或一个。你在其他地方使用过量词,(\d)?,你说的是零或一数字字符。但你真正想要的看起来更像是这样:

The essential thing to note here is that this regex will only match, at most, a two-character string! The character class, [ ... ], matches a single character: in your case, letters and whitespace. You need to combine this with what's called a quantifier, e.g. * meaning "zero or more", + meaning "one or more", and ? meaning "zero or one". You've used a quantifier elsewhere, (\d)?, where you're saying "zero or one" digit character. But what you really want looks more like this:

/^[a-zA-Z\s\d\/]+$/

这里,我们说一个或多个字母,空格,数字或斜杠(请注意,正斜杠必须使用反斜杠进行转义)。

Here, we're saying "one or more" letters, whitespace, digits, or slashes (note that the forward slash must be escaped using a backslash).

最后,你说要要求至少一个 数字。这可以通过正则表达式中更高级的构造来实现,称为外观断言。你想要这个:

Finally, you say want to require "at least one" digit. This can be achieved with a more advanced construct in regular expressions, called "lookaround assertions." You want this:

/^(?=.*\d)[a-zA-Z\s\d\/]+$/

特别是正向前瞻断言,你可以自己研究。另一种没有超前断言的方法是:

That, in particular, is a positive lookahead assertion, which you can research yourself. An alternate way of doing this, without lookahead assertions, would be:

/^[a-zA-Z\s\d\/]*\d[a-zA-Z\s\d\/]*$/

这显然更复杂,但是当你能够理解这一点时,你知道你正在理解正则表达式。祝你好运!

This is obviously more complicated, but when you're able to understand this, you know you're well on your way to understanding regular expressions. Good luck!

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

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