RegexBuilder · regex answers
Regex multiline flag explained
/^\w+/gm
Without m, ^ means start of string and matches exactly once. With m, it also matches after every line break, so this returns the first word of every line. The s flag is a different thing entirely: it makes . match newlines.
What each part does
| ^ | start of a line under the m flag |
| \w+ | a run of word characters |
| m | multiline — ^ and $ apply per line |
| g | global — keep going after the first match |
Tested against real input
Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.
| Input | Result | Matched |
|---|---|---|
| alpha\nbeta\ngamma | matches | alpha |
| one line only | matches | one |
| \n\n | no match | — |
The mistake to avoid
Confusing m with s. If you want . to cross line breaks you need the dotAll flag s, not multiline.
Try it on your own text
Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.
Open RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID