admin管理员组

文章数量:1426451

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)))

本文标签: JavaScript RegExFirst 2 characters letterrest numbers OR just numbersStack Overflow