2.5. Match Something at the Start and/or the End of a Line

Problem

Create four regular expressions. Match the word alpha, but only if it occurs at the very beginning of the subject text. Match the word omega, but only if it occurs at the very end of the subject text. Match the word begin, but only if it occurs at the beginning of a line. Match the word end, but only if it occurs at the end of a line.

Solution

Start of the subject

^alpha
Regex options: None (“^ and $ match at line breaks” must not be set)
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python
Aalpha
Regex options: None
Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby

End of the subject

omega$
Regex options: None (“^ and $ match at line breaks” must not be set)
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python
omega
Regex options: None
Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby

Start of a line

^begin
Regex options: ^ and $ match at line breaks
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

End of a line

end$
Regex options: ^ and $ match at line breaks
Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby

Discussion

Anchors and lines

The regular expression tokens ^, $, A, , and z are called anchors. They do not match any characters. Instead, they match at certain positions, effectively anchoring the regular expression match at those positions.

A line is the part of the subject text that lies between the start of the subject and a line break, between two line breaks, or between a line break and the end of the subject. If there are no line breaks in the subject, then the whole subject is considered to be one line. Thus, the following text consists of four lines, one each for one, two, an empty string, and four:

one
two

four

The text could be represented in a program as oneLFtwoLFLFfour.

Start of the subject

The anchor A always matches at the very start of the subject text, before the first character. That is the only place where it matches. Place A at the start of your regular expression to test whether the subject text begins with the text you want to match. The “A” must be uppercase.

JavaScript does not support A.

The anchor ^ is equivalent to A, as long as you do not turn on the “^ and $ match at line breaks” option. This option is off by default for all regex flavors except Ruby. Ruby does not offer a way to turn this option off.

Unless you’re using JavaScript, we recommend that you always use A instead of ^. The meaning of A never changes, avoiding any confusion or mistakes in setting regex options.

End of the subject

The anchors  and z always match at the very end of the subject text, after the last character. Place  or z at the end of your regular expression to test whether the subject text ends with the text you want to match.

.NET, Java, PCRE, Perl, and Ruby support both  and z. Python supports only . JavaScript does not support  or z at all.

The difference between  and z comes into play when the last character in your subject text is a line break. In that case,  can match at the very end of the subject text, after the final line break, as well as immediately before that line break. The benefit is that you can search for omega without having to worry about stripping off a trailing line break at the end of your subject text. When reading a file line by line, some tools include the line break at the end of the line, whereas others don’t;  masks this difference. z matches only at the very end of the subject text, so it will not match text if a trailing line break follows.

The anchor $ is equivalent to , as long as you do not turn on the “^ and $ match at line breaks” option. This option is off by default for all regex flavors except Ruby. Ruby does not offer a way to turn this option off. Just like , $ matches at the very end of the subject text, as well as before the final line break, if any.

To help clarify this subtle and somewhat confusing situation, let’s look at an example in Perl. Assuming that $/ (the current record separator) is set to its default , the following Perl statement reads a single line from the terminal (standard input):

$line = <>;

Perl leaves the newline on the content of the variable $line. Therefore, an expression such as endofinput.z will not match the variable. But endofinput. and endofinput.$ will both match, because they ignore the trailing newline.

To make processing easier, Perl programmers often strip newlines with:

chomp $line;

After that operation is performed, all three anchors will match. (Technically, chomp strips a string of the current record separator.)

Unless you’re using JavaScript, we recommend that you always use  instead of $. The meaning of  never changes, avoiding any confusion or mistakes in setting regex options.

Start of a line

By default, ^ matches only at the start of the subject text, just like A. Only in Ruby does ^ always match at the start of a line. All the other flavors require you to turn on the option to make the caret and dollar sign match at line breaks. This option is typically referred to as “multiline” mode.

Do not confuse this mode with “single line” mode, which would be better known as “dot matches line breaks” mode. “Multiline” mode affects only the caret and dollar sign; “single line” mode affects only the dot, as Recipe 2.4 explains. It is perfectly possible to turn on both “single line” and “multiline” mode at the same time. By default, both options are off.

With the correct option set, ^ will match at the start of each line in the subject text. Strictly speaking, it matches before the very first character in the file, as it always does, and also after each line break character in the subject text. The caret in ^ is redundant because ^ always matches after .

End of a line

By default, $ matches only at the end of the subject text or before the final line break, just like . Only in Ruby does $ always match at the end of each line. All the other flavors require you to turn on the “multiline” option to make the caret and dollar match at line breaks.

With the correct option set, $ will match at the end of each line in the subject text. (Of course, it also matches after the very last character in the text because that is always the end of a line as well.) The dollar in $ is redundant because $ always matches before .

Zero-length matches

It is perfectly valid for a regular expression to consist of nothing but one or more anchors. Such a regular expression will find a zero-length match at each position where the anchor can match. If you place several anchors together, all of them need to match at the same position for the regex to match.

You could use such a regular expression in a search-and-replace. Replace A or  to prepend or append something to the whole subject. Replace ^ or $, in “^ and $ match at line breaks” mode, to prepend or append something in each line in the subject text.

Combine two anchors to test for blank lines or missing input. A matches the empty string, as well as the string that consists of a single newline. Az matches only the empty string. ^$, in “^ and $ match at line breaks” mode, matches each empty line in the subject text.

Variations

(?m)^begin
Regex options: None
Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python
(?m)end$
Regex options: None
Regex flavors: .NET, Java, XRegExp, PCRE, Perl, Python

If you cannot turn on “^ and $ match at line breaks” mode outside the regular expression, you can place a mode modifier at the start of the regular expression. The concept of mode modifiers and JavaScript’s lack of support for them are both explained in the subsection Case-insensitive matching under Recipe 2.1.

(?m) is the mode modifier for “^ and $ match at line breaks” mode in .NET, Java, XRegExp, PCRE, Perl, and Python. The m stands for “multiline” mode, which is Perl’s confusing name for “^ and $ match at line breaks.”

As explained earlier, the terminology was so confusing that the developer of Ruby’s regex engine copied it incorrectly. Ruby uses (?m) to turn on “dot matches line breaks” mode. Ruby’s (?m) has nothing to do with the caret and dollar anchors. In Ruby, ^ and $ always match at the start and end of each line.

Except for the unfortunate mix-up in letters, Ruby’s choice to use ^ and $ exclusively for lines is a good one. Unless you’re using JavaScript, we recommend that you copy this choice in your own regular expressions.

Jan Goyvaerts followed the same idea in his designs of EditPad Pro and PowerGREP. You won’t find a checkbox labeled “^ and $ match at line breaks,” even though there is one labeled “dot matches line breaks.” Unless you prefix your regular expression with (?-m), you’ll have to use A and  to anchor your regex to the beginning or end of your file.

See Also

Recipe 3.4 explains how to set options such as “^ and $ match at line breaks” in your source code.

Recipe 3.21 shows how to use procedural code to really make a regex process some text line by line.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset