Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

After reading from the Perl Blackbook I don't see any difference between these regex assertions. Can someone explain them?

The difference between ^ which matches the beginning of a string and \A which matches at the beginning of the string.

The difference between $ which matches the end of a string and \Z and \z which match the end of the string.

The explanations seem to make these sound like they're identical, but there must be a difference, right?

Replies are listed 'Best First'.
Re: misc. regex questions
by duff (Parson) on Apr 11, 2004 at 03:54 UTC

    From perlre:

    The "\A" and "\Z" are just like "^" and "$",except that they won’t match multiple times when the "/m" modifier is used, while "^" and "$" will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use "\z".
Re: misc. regex questions
by ysth (Canon) on Apr 11, 2004 at 05:44 UTC
    To try to clarify duff's quote:

    ^ and \A are usually the same; it's only with the //m modifier that they differ (since then ^ will match at the beginning of the string or after a newline, \A can still be used to match only the beginning of the string).

    $ and \Z are usually the same (matching at the end of the string or just before a newline at the end of the string) but, again, differ with //m (where $ will match at the end of the string or before any newline). \z differs from either in that it matches only the end of the string, with or without //m.

      ^ and \A are NEVER the same. They may match the same thing in some cases but they are never the same.
        By "same" I meant "match (or don't match) in the same circumstances [in the absence of the m flag]". Is this just a semantic quibble or are you saying this expanded phrase is not accurate?