0

I need to check whether information entered are 3 character long, first one should be 0-9 second A-Z 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[A-Z] check only one character or whole string ?
  • Does + separate(split?) out characters?
Alnitak
341k72 gold badges420 silver badges503 bronze badges
asked Aug 7, 2012 at 11:04

4 Answers 4

1

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
answered Aug 7, 2012 at 11:11
Sign up to request clarification or add additional context in comments.

Comments

1

+ means one or more characters so a possible String would be ABCD1234EF or A3B, invalid is 3B or A 6B

Manse
38.1k11 gold badges88 silver badges112 bronze badges
answered Aug 7, 2012 at 11:09

1 Comment

the + symbol without being highlighted as code creates a list !
0

This is the regex you need :

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

In this case, does[A-Z] 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.

answered Aug 7, 2012 at 11:07

Comments

0

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

/^\w{1}\d{1}\w{1}$/
answered Aug 7, 2012 at 11:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.