JavaScript RegEx - First 2 characters letter, rest numbers OR just numbers - Stack Overflow

So I'm pletely new to RegEx and I've read a few things and it's just blown my mind.So fa

So I'm pletely new to RegEx and I've read a few things and it's just blown my mind.

So far this is what I have

/^([a-z]{2})?([0-9])/i

What I basically have is a text box that needs to accept a string where the first 2 characters are letters and the rest are numbers, or just numbers.

Examples.

Match:
AB12345
12345

Not a match:
12345AB
AB12345AB
ACD1123
A332

Any help and information would be great so I can see how it works and hopefully understand it myself!

Thanks!

So I'm pletely new to RegEx and I've read a few things and it's just blown my mind.

So far this is what I have

/^([a-z]{2})?([0-9])/i

What I basically have is a text box that needs to accept a string where the first 2 characters are letters and the rest are numbers, or just numbers.

Examples.

Match:
AB12345
12345

Not a match:
12345AB
AB12345AB
ACD1123
A332

Any help and information would be great so I can see how it works and hopefully understand it myself!

Thanks!

Share Improve this question edited Aug 14, 2018 at 16:52 bobble bubble 18.7k4 gold badges31 silver badges50 bronze badges asked Aug 14, 2018 at 15:36 user1469914user1469914 511 silver badge10 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You could take the start ^ and end $ of the string as well for checking, beside a quantifier for digits, one or more +.

/^([a-z]{2})?\d+$/i

console.log(
    ['AB12345', '12345', '12345AB', 'AB12345AB', 'ACD1123', 'A332']
        .map(s => /^([a-z]{2})?\d+$/i.test(s))
);

You miss end anchor($) and digit repetition(\d+):

const reg = /^([a-z]{2})?([0-9]+)$/i

console.log(['AB12345', '12345'].map(v => reg.test(v)))

console.log(['12345AB', 'AB12345AB', 'ACD1123', 'A332'].map(v => reg.test(v)))

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745463271a4628804.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信