开发者

match pattern in javascript

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

For eg. ABC-XY

开发者_StackOverflow社区

Thanks in advance.


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:

  • Regular Expressions
  • The RegExp Object
  • Using Regular Expressions with JavaScript


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

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


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


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

it will match A-Za-z_ though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜