简体   繁体   English

jQuery中的正则表达式仅允许一次匹配

[英]Regular expression in jquery allow only one match

Okay, i've got the following problem. 好的,我遇到了以下问题。 I used jquery to test a string with a regular expression. 我使用jquery测试带有正则表达式的字符串。 It works all fine, but.... 一切正常,但是....

In the Netherlands the zipcodes are 4 digits followed by 2 characters eg 1234AB. 在荷兰,邮政编码是4位数字,后跟2个字符,例如1234AB。 Now i use the following regex to find this: [0-9]{4}[AZ]{2} . 现在,我使用以下正则表达式来找到它: [0-9]{4}[AZ]{2}

But when someone types 1234AB+948203848 for example. 但是,例如,当有人键入1234AB + 948203848时。 It also return true. 它还返回true。 And i don't want that! 而且我不想要那个! How can i make it return false when it's not 4 digits followed by 2 characters? 如果它不是4位数字后跟2个字符,我如何使它返回false?

Thanks in advance. 提前致谢。

JSBIN JSBIN

Use anchors ^ and $ . 使用锚点^$ So your regex would become: 因此,您的正则表达式将变为:

/^\d{4}[A-Z]{2}$/

Just use anchors to indicate the beginning of the word ( ^ ) and the end of it ( $ ): 只需使用锚点来表示单词的开头( ^ )和结尾( $ ):

var patt = new RegExp("^[0-9]{4}[A-Z]{2}$");
                       ^                ^

As per your comments, you also want to capitalize the input. 根据您的评论,您还希望将输入大写。 For this, you can use .toUpperCase() : 为此,您可以使用.toUpperCase()

Test ---> JSBIN 测试---> JSBIN

$(document).ready(function(){
            $('[name=postcode]').keyup(function(){
            var str = $(this).val().toUpperCase();
            var patt = new RegExp("^[0-9]{4}[A-Z]{2}$");
            var res = patt.test(str);
                console.log(res);
            });
      });

Alternatively, you can use ^[0-9]{4}[a-zA-Z]{2}$ (note the [a-zA-Z] part) to check the four letters, no matter upper or lowercase. 或者,您可以使用^[0-9]{4}[a-zA-Z]{2}$ (请注意[a-zA-Z]部分)来检查四个字母,无论大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM