admin管理员组

文章数量:1391951

I am trying to match a string that has the form:

abcd:vxyz

That is: 4 chars followed by a colon then followed by three (or maximum) 4 chars.

I want to do case INSENSITIVE matches.

Can anyone help with the pattern?

I am trying to match a string that has the form:

abcd:vxyz

That is: 4 chars followed by a colon then followed by three (or maximum) 4 chars.

I want to do case INSENSITIVE matches.

Can anyone help with the pattern?

Share Improve this question edited Feb 21, 2011 at 23:46 p.campbell 101k70 gold badges262 silver badges326 bronze badges asked Feb 21, 2011 at 23:35 oompahloompahoompahloompah 9,34321 gold badges65 silver badges90 bronze badges 2
  • 2 If this is easy (and it is) what did you try before posting a question for all posterity on Stack Overflow? – Phrogz Commented Feb 21, 2011 at 23:42
  • 2 @Phrogz: Because I don't think its an effective use of my time (being predominantly a C++ programmer) to spend an hour or so on figuring out the expression - whilst it will take a Javascript expert less than a minute to figure it out (the first answers were posted under a minute). I don't have an ego, and I know what my strengths and weaknesses are. I don't mind asking for help from experts if the subject matter is not my area of expertise. – oompahloompah Commented Feb 21, 2011 at 23:55
Add a ment  | 

4 Answers 4

Reset to default 5
/^[a-z]{4}:[a-z]{3,4}$/i

........

The following regex should work:

"^[a-zA-Z]{4}:[a-zA-Z]{3,4}$"

The {4} part indicates that it should match exactly four copies of the previous symbol, which can be any character between 'a' and 'z', as well as 'A' and 'Z', inclusive.

The {3,4} part creates a range of copies between 3 and 4 inclusive, while the '^' symbol indicates that it should start at the beginning of the given string and the '$' sign indicates that it should end at the end of the given string.

Your example was alphabetical, but it was unclear if your desired regex should be limited to that. If you wanted to match any characters in those groups:

/^.{4}:.{3,4}$/i

Another non-regex way to do this would be to split() on the colon. Check for length 4 on the first element, and length 3 or 4 on the second element.

var foo = 'abcd:123a';
var bar = 'fds:0';

var af = foo.split(':');
var isMatch = ((af[0].length==4) && (af[1].length==3 || af[1].length==4));
alert (isMatch);

var ab = bar.split(':');
alert ((ab[0].length==4) && (ab[1].length==3 || ab[1].length==4));

本文标签: javascriptcaseinsensitive regex for colon in a stringStack Overflow