DebugPointer
Published on

Regex for min and max length

Regex for min and max length

Length of a string is defined by the total number of charcters in the string. In this article let's understand how we can create a regex for minimum and maximum length of a string and how regex can be matched for a length of a string.

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 length of a string

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 string length is between min and max value

Regular Expression for min and max length of a string name is represented by-

/^.{min,max}$/gm

For example, if we want to check if the string length is between 1 and 10 characters, the regex will be-

/^.{1,10}$/gm

Another example, if we want to check if the string length is between 5 and 10 characters, the regex will be-

/^.{5,10}$/gm

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

Input StringMatch Output
hidoes not match
how are you?does not match
hellomatches
bozzmobmatches
poppymatches

Here is a detailed explanation of the above regex-

/^.{5,10}$/gm

^ asserts position at start of a line
. matches any character (except for line terminators)
{5,10} matches the previous token between 5 and 10 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 string has length between min and max value or not.