4.10. Limit the Number of Lines in Text

Problem

You need to check whether a string is composed of five or fewer lines, without regard for how many total characters appear in the string.

Solution

The exact characters or character sequences used as line separators can vary depending on your operating system’s convention, application or user preferences, and so on. Crafting an ideal solution therefore raises questions about what conventions for indicating the start of a new line should be supported. The following solutions support the standard MS-DOS/Windows (\r\n), legacy Mac OS (\r), and Unix/Linux/BSD/OS X (\n) line break conventions.

Regular expression

The following three flavor-specific regexes contain two differences. The first regex uses atomic groups, written as (?>), instead of noncapturing groups, written as (?:), because they have the potential to provide a minor efficiency improvement here for the regex flavors that support them. Python and JavaScript do not support atomic groups, so they are not used with those flavors. The other difference is the tokens used to assert position at the beginning and end of the string (\A or ^ for the beginning of the string, and \z, \Z, or $ for the end). The reasons for this variation are discussed in depth later in this recipe. All three flavor-specific regexes, however, match exactly the same strings:

\A(?>[^\r\n]*(?>\r\n?|\n)){0,4}[^\r\n]*\z
Regex options: None
Regex flavors: .NET, Java, PCRE, Perl, Ruby
\A(?:[^\r\n]*(?:\r\n?|\n)){0,4}[^\r\n]*\Z
Regex options: None
Regex flavor: Python
^(?:[^\r\n]*(?:\r\n?|\n)){0,4}[^\r\n]*$
Regex options: None (“^ and $ match at line breaks” must not be set)
Regex flavor: JavaScript

PHP (PCRE) example

if (preg_match('/\A(?>[^\r\n]*(?>\r\n?|\n)){0,4}[^\r\n]*\z/', 
               $_POST['subject'])) {
    print 'Subject contains five or fewer lines';
} else {
    print 'Subject contains more than five lines';
}

See Recipe 3.6 for help implementing these regular expressions with other programming languages.

Discussion

All of the regular expressions shown so far in this recipe use a grouping that matches any number of non-line-break characters followed by an MS-DOS/Windows, legacy Mac OS, or Unix/Linux/BSD/OS X line break sequence. The grouping is repeated between zero and four times, since four line breaks occur in five lines of text. After the grouping, we allow one last sequence of non-line-break characters to fill out the fifth line, if present.

In the following example, we’ve broken up the first version of the regex into its individual parts. We’ll explain the variations for alternative regex flavors afterward:

\A          # Assert position at the beginning of the string.
(?>         # Group but don't capture or keep backtracking positions:
  [^\r\n]*  #   Match zero or more characters except CR and LF.
  (?>       #   Group but don't capture or keep backtracking positions:
    \r\n?   #     Match a CR, with an optional following LF (CRLF).
   |        #    Or:
    \n      #     Match a standalone LF character.
  )         #   End the noncapturing, atomic group.
){0,4}      # End group; repeat between zero and four times.
[^\r\n]*    # Match zero or more characters except CR and LF.
\z          # Assert position at the end of the string.
Regex options: Free-spacing
Regex flavors: .NET, Java, PCRE, Perl, Ruby

The leading \A matches the position at the beginning of the string, and \z matches at the end. This helps to ensure that the entire string contains no more than five lines, because unless the regex is anchored to the start and end of the text, it can match any five lines within a longer string.

Next, an atomic group (see Recipe 2.14) encloses a character class that matches any number of non-line-break characters and a subgroup that matches one line break sequence. The character class is optional (in that its following quantifier allows it to repeat zero times), but the subgroup is required and must match exactly one line break per repetition of the outer group. The outer group’s immediately following quantifier allows it to repeat between zero and four times. Zero repetitions allows matching a completely empty string, or a string with only one line (no line breaks).

Following the outer group is another character class that matches zero or more non-line-break characters. This lets the regex fill in the match with the fifth line of subject text, if present. We can’t simply omit this class and change the preceding quantifier to {0,5}, because then the text would have to end with a line break to match at all. So long as the last line was empty, it would also allow matching six lines, since six lines are separated by five line breaks. That’s no good.

In all of these regexes, the subgroup matches any of three line break sequences:

  • A carriage return followed by a line feed (\r\n, the conventional MS-DOS/Windows line break sequence)

  • A standalone carriage return (\r, the legacy Mac OS line break character)

  • A standalone line feed (\n, the conventional Unix/Linux/BSD/OS X line break character)

Now let’s move on to the cross-flavor differences.

The first version of the regex (used by all flavors except Python and JavaScript) uses atomic groups rather than simple noncapturing groups. Although in some cases the use of atomic groups can have a much more profound impact, in this case they simply let the regex engine avoid a bit of unnecessary backtracking that can occur if the match attempt fails.

The other cross-flavor differences are the tokens used to assert position at the beginning and end of the string. All of the regex flavors discussed here support ^ and $, so why do some of the regexes use \A, \Z, and \z instead? The short explanation is that the meaning of these metacharacters differs slightly between regular expression flavors. The long explanation leads us to a bit of regex history….

When using Perl to read a line from a file, the resulting string ends with a line break. Hence, Perl introduced an “enhancement” to the traditional meaning of $ that has since been copied by most regex flavors. In addition to matching the absolute end of a string, Perl’s $ matches just before a string-terminating line break. Perl also introduced two more assertions that match the end of a string: \Z and \z. Perl’s \Z anchor has the same quirky meaning as $, except that it doesn’t change when the option to let ^ and $ match at line breaks is set. \z always matches only the absolute end of a string, no exceptions. Since this recipe explicitly deals with line breaks in order to count the lines in a string, it uses the \z assertion for the regex flavors that support it, to ensure that an empty, sixth line is not allowed.

Most of the other regex flavors copied Perl’s end-of-line/string anchors. .NET, Java, PCRE, and Ruby all support both \Z and \z with the same meanings as Perl. Python includes only \Z (uppercase), but confusingly changes its meaning to match only the absolute end of the string, just like Perl’s lowercase \z. JavaScript doesn’t include any “z” anchors, but unlike all of the other flavors discussed here, its $ anchor matches only at the absolute end of the string (when the option to let ^ and $ match at line breaks is not enabled).

As for \A, the situation is somewhat better. It always matches only at the start of a string, and it means exactly the same thing in all flavors discussed here, except JavaScript (which doesn’t support it).

Tip

Although it’s unfortunate that these kinds of confusing cross-flavor inconsistencies exist, one of the benefits of using the regular expressions in this book is that you generally won’t need to worry about them. Gory details like the ones we’ve just described are included in case you care to dig deeper.

Variations

Working with esoteric line separators

The previously shown regexes limit support to the conventional MS-DOS/Windows, Unix/Linux/BSD/OS X, and legacy Mac OS line break character sequences. However, there are several rarer vertical whitespace characters that you might occasionally encounter. The following regexes take these additional characters into account while limiting matches to five lines of text or fewer

\A(?>\V*\R){0,4}\V*\z
Regex options: None
Regex flavors: PCRE 7.2 (with the PCRE_BSR_UNICODE option), Perl 5.10
\A(?>[^\n-\r\x85\x{2028}\x{2029}]*(?>\r\n?|↵
[\n-\f\x85\x{2028}\x{2029}])){0,4}[^\n-\r\x85\x{2028}\x{2029}]*\z
Regex options: None
Regex flavors: Java 7, PCRE, Perl
\A(?>[^\n-\r\u0085\u2028\u2029]*(?>\r\n?|↵
[\n-\f\u0085\u2028\u2029])){0,4}[^\n-\r\u0085\u2028\u2029]*\z
Regex options: None
Regex flavors: .NET, Java, Ruby 1.9
\A(?>[^\n-\r\x85\u2028\u2029]*(?>\r\n?|↵
[\n-\f\x85\u2028\u2029])){0,4}[^\n-\r\x85\u2028\u2029]*\z
Regex options: None
Regex flavors: .NET, Java
\A(?:[^\n-\r\x85\u2028\u2029]*(?:\r\n?|↵
[\n-\f\x85\u2028\u2029])){0,4}[^\n-\r\x85\u2028\u2029]*\Z
Regex options: None
Regex flavor: Python
^(?:[^\n-\r\x85\u2028\u2029]*(?:\r\n?|↵
[\n-\f\x85\u2028\u2029])){0,4}[^\n-\r\x85\u2028\u2029]*$
Regex options: None (“^ and $ match at line breaks” must not be set)
Regex flavor: JavaScript

Ruby 1.8 does not support Unicode regular expressions, and therefore cannot use any of these options. Ruby 1.9 does not support the shorter \xNN syntax for non-ASCII character positions (anything greater than 0x7F), and therefore must use \u0085 instead of \x85.

All of these regexes handle the line separators in Table 4-1, listed with their Unicode positions and names. This list comprises the characters that the Unicode standard recognizes as line terminators.

Table 4-1. Line separators

Unicode sequence

Regex equivalent

Name

Abbr.

Common usage

U+000D U+000A

\r\n

Carriage return and line feed

CRLF

Windows and MS-DOS text files

U+000A

\n

Line feed

LF

Unix, Linux, BSD, and OS X text files

U+000B

\v or \x0B

Line tabulation (aka vertical tab)

VT

(Rare)

U+000C

\f

Form feed

FF

(Rare)

U+000D

\r

Carriage return

CR

Legacy Mac OS text files

U+0085

\x85 or \u0085

Next line

NEL

IBM mainframe text files

U+2028

\u2028 or \x{2028}

Line separator

LS

(Rare)

U+2029

\u2029 or \x{2029}

Paragraph separator

PS

(Rare)

See Also

Recipe 4.9 shows how to limit the length of text based on characters and words, rather than lines.

Techniques used in the regular expressions in this recipe are discussed in Chapter 2. Recipe 2.2 explains how to match nonprinting characters. Recipe 2.3 explains character classes. Recipe 2.5 explains anchors. Recipe 2.7 explains how to match Unicode characters. Recipe 2.9 explains grouping. Recipe 2.12 explains repetition. Recipe 2.14 explains atomic groups.

Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.