January 13, 20232 min read

Regex for min and max length

The min and max number limit is defined by the value of the number it can take in the range. In this article let's understand how we can create a regex for minimum and maximum number and how regex can be matched for a number.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Structure of a min and max number

The month should have the following criteria and structure-

  • A string is a series of characters with a given length
  • It has to be in the range of min and max value

Regex for checking if the number is between min and max value or length

Regular Expression for min and max number name is represented by-


For example, if we want to check if the number is between 1 and 2 digits i.e., from 0 to 99, the regex will be-


Another example, if we want to check if the number is between 1 and 5 digits i.e., from 0 to 99999, the regex will be-


Test string examples for the above regex with 5 to 10 min and max limits-

Input StringMatch Output
hidoes not match
12342535123does not match

Here is a detailed explanation of the above regex-


^ asserts position at start of a line
\d matches a digit (equivalent to [0-9])
{1,5} matches the previous token between 1 and 5 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Hope this article was useful to check if the number has length between min and max value or not.

Share this blog
Tagged in :
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles
Previous Article
January 13, 20232 min read
Next Article
January 13, 20232 min read