简体   繁体   中英

RegExp issues - character limit and whitespace ignoring

I need to validate a string that can have any number of characters, a comma, and then 2 characters. I'm having some issues. Here's what I have:

var str="ab,cdf"; 
var patt1=new RegExp("[A-z]{2,}[,][A-z]{2}");
if(patt1.test(str)) {
    alert("true");
}
else {
    alert("false");
}

I would expect this to return false, as I have the {2} limit on characters after the comma and this string has three characters. When I run the fiddle , though, it returns true. My (admittedly limited) understanding of RegExp indicates that {2,} is at least 2, and {2} is exactly two, so I'm not sure why three characters after the comma are still returning true.

I also need to be able to ignore a possible whitespace between the comma and the remaining two characters. (In other words, I want it to return true if they have 2+ characters before the comma and two after it - the two after it not including any whitespace that the user may have entered.)

So all of these should return true:

var str = "ab, cd";
var str = "abc, cd";
var str = "ab,cd";
var str = "abc,dc";

I've tried adding the \\S indicator after the comma like this:

var patt1=new RegExp("[A-z]{2,}[,]\S[A-z]{2}");

But then the string returns false all the time, even when I have it set to ab, cd , which should return true.

What am I missing?

{2,} is at least 2, and {2} is exactly two, so I'm not sure why three characters after the comma are still returning true.

That's correct. What you forgot is to anchor your expression to string start and end - otherwise it returns true when it occurs somewhere in the string.

not including any whitespace: I've tried adding the \\S indicator after the comma

That's the exact opposite. \\s matches whitespace characters, \\S matches all non-whitespace characters. Also, you probably want some optional repetition of the whitespace, instead of requiring exact one.

 [Az] 

Notice that this character range also includes the characters between Z and a , namely []^_` . You will probably want [A-Za-z] instead, or use [az] and make your regex case-insensitive.

Combined, this is what your regex should look like (using a regular expression literal instead of the RegExp constructor with a string literal):

var patt1 = /^[a-z]{2,},\s*[a-z]{2}$/i;

You are missing ^ , $ .Also the range should be [a-zA-Z] not [Az]

Your regex should be

^[a-zA-Z]{2,}[,]\s*[A-Za-z]{2}$

^ would match string from the beginning...

$ would match string till end.

Without $ , ^ it would match anywhere in between the string

\\s* would match 0 to many space..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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