加拿大邮政编码功能的高效正则表达式 [英] Efficient regex for Canadian postal code function

查看:295
本文介绍了加拿大邮政编码功能的高效正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var regex = /[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d/;
var match = regex.exec(value);
if (match){
    if ( (value.indexOf("-") !== -1 || value.indexOf(" ") !== -1 ) && value.length() == 7 ) {
        return true;
    } else if ( (value.indexOf("-") == -1 || value.indexOf(" ") == -1 ) && value.length() == 6 ) {
        return true;
    }
} else {
        return false;
}

正则表达式寻找模式A0A 1B1。
真实测试:

The regex looks for the pattern A0A 1B1. true tests:

A0A 1B1

A0A-1B1

A0A1B1

A0A1B1C<<问题孩子

A0A1B1C << problem child

因此我添加了 - 或的支票,然后检查了长度。

so I added a check for "-" or " " and then a check for length.

是否有正则表达式或更有效的方法?

Is there a regex, or more efficient method?

推荐答案

为您的模式添加锚点:

var regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;

^ 表示字符串的开头和 $ 表示字符串结束。添加这些锚点将阻止 C 滑入匹配,因为您的模式现在将期望整个字符串由6个(有时7个作为空格)字符组成。这个额外的奖励现在应该减轻您必须随后检查字符串长度。

^ means "start of string" and $ means "end of string". Adding these anchors will prevent the C from slipping in to the match since your pattern will now expect a whole string to consist of 6 (sometimes 7--as a space) characters. This added bonus should now alleviate you of having to subsequently check the string length.

此外,由于您似乎想要允许连字符,您可以将其放入可选项包含您最初使用的空间的字符类。务必将连字符保留为第一个或最后一个字符;否则,您将需要将其转义(使用前导反斜杠)以防止正则表达式引擎将其解释为字符范围的一部分(例如 AZ )。

Also, since it appears that you want to allow hyphens, you can slip that into an optional character class that includes the space you were originally using. Be sure to leave the hyphen as either the very first or very last character; otherwise, you will need to escape it (using a leading backslash) to prevent the regex engine from interpreting it as part of a character range (e.g. A-Z).

这篇关于加拿大邮政编码功能的高效正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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