views:

49

answers:

4

How can i match a expression in which first three characters are alphabets followed by a "-" and than 2 alphabets.

For eg. ABC-XY

Thanks in advance.

+1  A: 
[A-Z]{3}-[A-Z]{2}

if you also want to allow lowercase, change A-Z to A-Za-z.

Amber
A: 
/^[a-zA-Z]{3}-[a-zA-Z]{2}$/
Asaph
+2  A: 

If you want only to test if the string matchs the pattern, use the test method:

function isValid(input) {
 return /^[A-Z]{3}-[A-Z]{2}$/.test(input);
}

isValid("ABC-XY"); // true
isValid("ABCD-XY"); // false

Basically the /^[A-Z]{3}-[A-Z]{2}$/ RegExp looks for:

  • The beginning of the string ^
  • Three uppercase letters [A-Z]{3}
  • A dash literally -
  • Two more uppercase letters [A-Z]{2}
  • And the end of the string $

If you want to match alphanumeric characters, you can use \w instead of [A-Z].

Resources:

CMS
A: 
/\w{3}-\w{2}/.test("ABC-XY")
true

it will match A-Za-z_ though.

S.Mark