Hone

Lessons · Regex · ^ and $: once, or once per line

One start, or one per line

Without MULTILINE, ^ means the start of the STRING. With it, ^ also matches just after every newline -- and $ moves with it.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The moment you read a file in one go instead of line by line, every line but the first is in the middle of the string as far as ^ is concerned.

How to think about it

Ask whether 'the start' means the start of the text or the start of a line. The flag is the answer to that question and nothing else.

Worked example

re.findall(r'^\w+', 'one two\nthree four')
One start, so one match.
re.findall(r'^\w+', 'one two\nthree four', re.M)
A start per line.
re.findall(r'\w+$', 'one two\nthree four', re.M)
The same flag moved $ as well.

Your turn

Match the first word of EVERY line.

re.findall(r'^\w+', 'one two\nthree four', re.)

The trap

MULTILINE is about ^ and $. It does nothing to the dot; that is DOTALL, and the two are constantly swapped.

Practise ^ and $: once, or once per line on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.