How do anchors match the start or end of a line in Python and JavaScript?
Quick answer
By default, ^ and $ mark the start and end of the whole input in both Python and JavaScript. Multiline mode makes them mark line boundaries too: use re.MULTILINE (or (?m)) in Python and the m flag in JavaScript. For first\nsecond, ^second$ matches only with multiline mode, at offsets 6 through 12.
The question, the details, the next step.
A practical checklist
Decide whether the target is the entire input or one line inside it.
Use
^and$for start and end assertions; they do not consume characters.For line boundaries, enable Python
re.MULTILINEor(?m), or JavaScript’smflag.Test with input containing a newline, such as
first\nsecond.Check the match location:
secondspans offsets 6 to 12 in this sample.
A few more useful answers
Does the `m` flag mean that the dot matches newlines?
Here, m refers to changing what ^ and $ match: they can mark line boundaries. Dot behavior is a separate regex feature, so check the documentation for the language or engine you are using.
Why do the Python and JavaScript examples show different span formats?
The examples use each language’s match interface: Python’s span() returns a start-and-end pair, while the JavaScript example combines index and the matched text’s length to show those offsets.
What if I only want to find the word `second`, wherever it appears?
Remove the anchors and search for second. Keep ^ and $ when the match must occupy the relevant whole input or, with multiline mode, a whole line.
Sources
References used for this guide.
- [S1] Python 3.11 re documentation: Start and end anchors and MULTILINE docs.python.org · Checked
- [S2] MDN JavaScript regex assertions: String and line boundaries developer.mozilla.org · Checked
