1

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
  • That very sentence pretty much spells out the answer for you.... if you know regexes at all. Commented Nov 19, 2009 at 6:33

4 Answers 4

4

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:

Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

0
/^[a-zA-Z]{3}-[a-zA-Z]{2}$/

Comments

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

it will match A-Za-z_ though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.