Skip to Content
Regular Expressions Cookbook
book

Regular Expressions Cookbook

by Jan Goyvaerts, Steven Levithan
May 2009
Intermediate to advanced
510 pages
15h
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook

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

if ($ARGV[0] =~ /^[A-Z]{1,10}$/) {
    print "Input is valid\n";
} else {
    print "Input is invalid\n";
}

Other programming languages

See Recipe 3.5 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, PCRE, Perl, Python, Ruby

The ^

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Regular Expressions Cookbook, 2nd Edition

Regular Expressions Cookbook, 2nd Edition

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9780596802837Catalog PageErrata