最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Javascript Regex to validate string length and last 3 characters as digits - Stack Overflow

matteradmin6PV0评论

How should I write regex to validate below conditions:

  • Total length of string should be between 4 to 6
  • Last 3 characters should be digits only.
  • String is only alphanumeric

eg: Valid strings: 1234, EC123, 1YC898, 001234

So far, I have tried below regex, but seems like I am missing something?

(^[a-zA-Z0-9]{4,6})?\d{3}$

How should I write regex to validate below conditions:

  • Total length of string should be between 4 to 6
  • Last 3 characters should be digits only.
  • String is only alphanumeric

eg: Valid strings: 1234, EC123, 1YC898, 001234

So far, I have tried below regex, but seems like I am missing something?

(^[a-zA-Z0-9]{4,6})?\d{3}$
Share Improve this question asked Jul 21, 2014 at 17:35 johnk1johnk1 2478 silver badges19 bronze badges 2
  • debuggex. is great for trying your pattern and seeing why it works, or not, when you change it. The question is: what are you really trying to match. Is this homework with nonsense strings, or are you actually trying to find real strings from real data that need to match a specific pattern? – Mike 'Pomax' Kamermans Commented Jul 21, 2014 at 17:37
  • Thanks for the link Mike. I am using regexr.. This is for one of my SAP UI5 application. Need to set a validation regex for one of the input field. – johnk1 Commented Jul 21, 2014 at 17:48
Add a ment  | 

1 Answer 1

Reset to default 5

You can use:

^[a-zA-Z0-9]{1,3}\d{3}$
  • ^[a-zA-Z0-9]{1,3} will match 1 to 3 alpha-numerals at the start
  • \d{3}$ will match 3 digits at the end of your input
Post a comment

comment list (0)

  1. No comments so far