Matching Locations within a String

At times, the pattern to be matched appears at either the very beginning or end of a string. In these cases, use a caret "^" to match a desired pattern at the beginning of a string, and a dollar sign "$" for the end of the string. For example, the regular expression email matches anywhere along the following strings: "email", "emailing", "bogus_emails", and "smithsemailaddress". However, the regex ^email only matches the strings "email" and "emailing". The caret "^" in this example is used to effectively anchor the match to the start of the string. For this reason, both the caret "^" and dollar sign "$" are referred to as anchors in the regex syntax.

Note: The caret "^" has many meanings in regular expressions. Its function is determined by its context. The caret can be used as an anchor to match patterns at the beginning of a string, for example:(^File). The caret can also be used as a logical "NOT" to negate content in a character class, for example: [^...].

Using anchors to match at the beginning or end of a string.

Example 1: Use "$" to match the ".com" pattern at the end of a string.

  • Regex:
    .*\.com$
  • Matches:
    mydomain.com 
    a.b.c.com
  • Doesn't Match:
    mydomain.org 
    mydomain.com.org

Example 2: Use "^" to match "inter" at the beginning of a string, "$" to match "ion" at the end of a string, and ".*" to match any number of characters within the string.

  • Regex:
    ^inter.*ion$
  • Matches:
    internationalization
    internalization
  • Doesn't Match:
    reinternationalization

Example 3: Use "^" inside parentheses to match "To" and "From" at the beginning of the string.

  • Regex:
    (^To:|^From:)(Smith|Chan)
  • Matches:
    From:Chan
    To:Smith
    From:Smith 
    To:Chan
  • Doesn't Match:
    From: Chan
    from:Smith
    To Chan

Example 4: Performing the same search as #3, place the caret "^" outside the parentheses this time for similar results.

  • Regex:
    ^(From|Subject|Date):(Smith|Chan|Today)
  • Matches:
    From:Smith
    Subject:Chan 
    Date:Today
  • Doesn't Match:
    X-Subject:
    date:Today