简体   繁体   中英

Using regular expression in Javascript

I need to check whether information entered are 3 character long, first one should be 0-9 second AZ and third 0-9 again.

I have written pattern as below:

var pattern = `'^[A-Z]+[0-9]+[A-Z]$'`;
var valid = str.match(pattern);

I got confused with usage of regex for selecting, matching and replacing.

  • In this case, does [AZ] check only one character or whole string ?
  • Does + separate(split?) out characters?

+表示一个或多个字符,因此可能的字符串是ABCD1234EF或A3B,无效的是3B或A 6B

1) + matches one or more. You want exactly one

2) declare your pattern as a REGEX literal, inside forward slashes

With these two points in mind, your pattern should be

/^[A-Z][0-9][A-Z]$/

Note also you can make the pattern slightly shorter by replacing [0-9] with the \\d shortcut (matches any numerical character).

3) Optionally, add the case-insensitive i flag after the final trailing slash if you want to allow either case.

4) If you want to merely test a string matches a pattern, rather than retrieve a match from it, use test() , not match() - it's more efficient.

var valid = pattern.test(str); //true or false

This is the regex you need :

^[0-9][A-Z][0-9]$

In this case, does[AZ] check only one character or whole string ?

It's just check 1 char but a char can be many times in a string..

you should add ^ and $ in order to match the whole string like I did.

Does + separate(split?) out characters? no.

+ sign just shows that a chars can repeat 1+ times.

"+" means one or more. In your case you should use exact quantity match:

/^\w{1}\d{1}\w{1}$/

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