Regular Expressions Start of Line


Example

When multi-line (?m) modifier is turned off, ^ matches only the input string's beginning:

For the regex

^He

The following input strings match:

  • Hedgehog\nFirst line\nLast line
  • Help me, please
  • He

And the following input strings do not match:

  • First line\nHedgehog\nLast line
  • IHedgehog
  • Hedgehog (due to white-spaces )

When multi-line (?m) modifier is turned on, ^ matches every line's beginning:

^He

The above would match any input string that contains a line beginning with He.

Considering \n as the new line character, the following lines match:

  • Hello
  • First line\nHedgehog\nLast line (second line only)
  • My\nText\nIs\nHere (last line only)

And the following input strings do not match:

  • Camden Hells Brewery
  • Helmet (due to white-spaces )

Matching empty lines using ^

Another typical use case for caret is matching empty lines (or an empty string if the multi-line modifier is turned off).

In order to match an empty line (multi-line on), a caret is used next to a $ which is another anchor character representing the position at the end of line (Anchor Characters: Dollar ($) ). Therefore, the following regular expression will match an empty line:

 ^$