regex multiline flag — ^ and $ match line start/end
Quick Answer
// JavaScript — use /m flag
const text = "first line\nsecond line\nthird line";
text.match(/^\w+/m) // ["first"] — only first line without /m
text.match(/^\w+/gm) // ["first", "second", "third"] — all lines
# Python
import re
re.findall(r'^\w+', text, re.MULTILINE)
# ['first', 'second', 'third']
Usage
Without the multiline flag, ^ matches only the start of the whole string, and $ matches only the end.
Other causes & fixes
DOTALL / single-line flag — . matches newlines
By default . does NOT match newline characters. The DOTALL flag changes this.
// JavaScript — use /s flag (ES2018+)
'first\nsecond'.match(/first.second/s) // matches
# Python
re.search(r'first.second', 'first\nsecond', re.DOTALL)
Combining flags
// JavaScript — multiline + global + case insensitive
text.match(/^pattern/gmi)
# Python — combine with |
re.findall(r'^pattern', text, re.MULTILINE | re.IGNORECASE)
Match end of each line with $
// Find lines ending with a semicolon
code.match(/^.*;$/gm)
Related