4.9. Limit the Length of Text
Problem
You want to test whether a string is composed of between 1 and 10 letters from A to Z.
Solution
All the programming languages covered by this book provide a
simple, efficient way to check the length of text. For example,
JavaScript strings have a length property that
holds an integer indicating the string’s length. However, using regular
expressions to check text length can be useful in some situations,
particularly when length is only one of multiple rules that determine
whether the subject text fits the desired pattern. The following regular
expression ensures that text is between 1 and 10 characters long, and
additionally limits the text to the uppercase letters A–Z. You can
modify the regular expression to allow any minimum or maximum text
length, or allow characters other than A–Z.
Regular expression
^[A-Z]{1,10}$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Perl example
if ($ARGV[0] =~ /^[A-Z]{1,10}$/) {
print "Input is valid\n";
} else {
print "Input is invalid\n";
}See Recipe 3.6 for help with implementing this regular expression with other programming languages.
Discussion
Here’s the breakdown for this very straightforward regex:
^ # Assert position at the beginning of the string.
[A-Z] # Match one letter from A to Z
{1,10} # between 1 and 10 times.
$ # Assert position at the end of the string.| Regex options: Free-spacing |
| Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python, Ruby |
The ‹^› and
‹$› anchors ensure ...