Regex find end of line
How regex finds the end of a line: what $ matches with and without multiline mode, how line endings and engines differ, and when a plain-text search is the better choice.
Finding the end of a line with a regular expression looks simple: put a dollar sign at the end of the pattern. In practice, what $ matches depends on the regex engine, whether multiline mode is on, and which line-ending characters the text contains. This review explains how end-of-line matching works, where it tends to fail, and when a plain-text approach is the safer choice. It is based on documented engine behavior. It does not include hands-on tests of any specific editor or online tester, so check the documentation for the exact tool you use.
Is regex end-of-line matching the right tool for your task?
Regex end-of-line anchors are a good fit when you need to act on the last characters of every line. Common examples are removing trailing whitespace, appending a semicolon, validating that each line ends in a certain token, or extracting the final field of each record. The main benefit is precision: an anchor ties the match to a position instead of to a guessed character, so the rest of the line is left alone.
The main drawback is portability. The same pattern can match different positions in JavaScript, Python, PCRE, Java and .NET. It can also behave differently on files with Windows (CRLF) line endings. A pattern that works in one tester can silently miss lines or produce extra matches elsewhere.
Plain text or simpler tools are often better in these cases:
- You only need to find or replace a literal line-break character. A non-regex find and replace that supports escape sequences, or splitting on the newline in your programming language, is clearer.
- You are processing data line by line anyway. Trimming each line with a string method avoids anchor and flag questions entirely.
- Other people will maintain the pattern but are not familiar with regex flags.
What the end-of-line anchor actually matches
The $ anchor is zero-width. It matches a position, not a character. It does not consume the line break. If you replace a match of $ with text, the text is inserted before the line break and the break stays in place. If you want to remove or change the line break itself, you have to match the break characters, such as \n or \r\n, explicitly.
Regex works on the stored characters of the text, not on how the text looks on screen:
- A line that an editor soft-wraps on screen still contains no line break at the wrap point, so $ does not match there.
- In right-to-left or mixed-direction text, the end of a line is the logical end of the stored character sequence. Visually, that end may appear on the left side of the line.
Default mode versus multiline mode
Without the multiline flag, $ refers to the end of the whole input, not to each line. Many engines (Perl, PCRE, Python, Java and .NET) also let $ match just before a single trailing newline at the very end of the input. JavaScript does not: without the m flag, $ matches only at the absolute end of the input.
With multiline mode on, $ also matches immediately before line terminators throughout the text. This is the setting most people mean when they ask how to find the end of every line. The flag is written as m in JavaScript and PCRE-style patterns, as the inline modifier (?m) in several engines, as re.MULTILINE in Python, as Pattern.MULTILINE in Java, and as RegexOptions.Multiline in .NET.
The following Python example shows the difference. The comments show the documented results.
import re
text = "a\nb\n"
re.sub(r"$", ";", text) # 'a\nb;\n;'
re.sub(r"$", ";", text, flags=re.M) # 'a;\nb;\n;'
Both results contain a semicolon after the final newline. This happens because $ matches both before the trailing newline and at the absolute end of the input. When you append text to every line, check whether the input ends with a line break; otherwise an extra empty line can gain a stray suffix. JavaScript shows the same final-position behavior with the m flag:
"a\nb\n".replace(/$/g, ";") // "a\nb\n;"
"a\nb\n".replace(/$/gm, ";") // "a;\nb;\n;"
Absolute end of input
If you need the true end of the input and want to ignore any trailing newline, most engines provide a separate anchor. In Perl, PCRE, Java and .NET this is \z. In those engines, \Z means the end of input or just before a final newline. Python's \Z means the absolute end, so the same letter means different things in different engines. JavaScript has neither anchor. There, use $ without the m flag.
How engines differ
| Engine | $ without multiline | $ with multiline | Absolute end | Any line break (\R) |
| JavaScript | End of input only | Before \n, \r, U+2028, U+2029, and at end | Not available | Not available |
| Python re | End, or before a final \n | Before every \n, and at end | \Z | Not available |
| Perl / PCRE | End, or before a final newline | Before every newline, and at end; the newline convention is configurable in PCRE | \z | Supported |
| Java | End, or before a final line terminator | Before \n, \r\n, \r, U+0085, U+2028, U+2029 (only \n with UNIX_LINES), and at end | \z | Supported (Java 8 and later) |
| .NET | End, or before a final \n | Before every \n, and at end | \z | Not available |
Line-oriented command-line tools such as grep apply each pattern to one line at a time with the newline already removed. In those tools, $ simply means the end of each line, and no multiline flag is involved.
Windows line endings and other pitfalls
The most common failure is CRLF text. Python, .NET and default PCRE treat only \n as the line terminator. In those engines, $ matches between the \r and the \n, so the \r is left at the end of what you think of as the line. A pattern that expects a word right before the end of the line will then miss every line except the last.
import re
text = "one\r\ntwo"
re.findall(r"\w+$", text, re.M) # ['two']
re.findall(r"\w+(?=\r?$)", text, re.M) # ['one', 'two']
The lookahead \r?$ accepts an optional carriage return before the anchor without including it in the match. The same issue affects line-based tools: in a CRLF file, a pattern like foo$ fails because the \r sits between foo and the end of the line. Where \R is supported, it matches any common line-break sequence, which is useful when you need to consume the break itself.
Other frequent surprises:
- \s matches line breaks. In multiline mode, \s+$ can match across blank lines and delete them when you only meant to strip trailing spaces. Use [ \t]+$ to limit the match to spaces and tabs.
- Characters such as the no-break space (U+00A0) are not matched by [ \t]. Whether \s matches them depends on the engine and its Unicode settings.
- The dot does not match line breaks by default, so .*$ stops at the end of the current line. The separate dotall or s flag changes that behavior. It is independent of multiline mode, and the two are often confused.
Does the pattern still work after copying or sharing it?
A pattern that works in one place can break when you paste it somewhere else. Check these points when moving a pattern between tools:
- Flags are often not part of the pattern text. A pattern copied from a tester may lose its multiline setting unless you use an inline modifier such as (?m) or pass the flag in code.
- Backslashes may need extra escaping. In ordinary string literals and in JSON, \r and \n may need doubled backslashes; raw strings, as in the Python examples above, avoid this.
- Shells can interfere with special characters. In shell commands, a $ inside double quotes can be interpreted by the shell before the regex engine sees it; single quotes avoid that.
- In replacement strings for JavaScript and .NET, $ introduces group references such as $1, so a literal dollar sign must be written as $$.
- Copying text between systems, or version-control settings that convert line endings, can change LF to CRLF or the reverse. This changes which positions $ matches.
Accessibility is rarely affected directly, because end-of-line matching changes stored text rather than its presentation. The output still matters, though. Removing line breaks or adding characters at line ends changes what screen readers announce and how text reflows. For any edit that will be published, review the result as plain text before you share it.
What to search for and where to find it
In engine documentation, the relevant topics are usually called anchors, line anchors, or end-of-line assertions. The setting that makes $ work per line is called multiline mode. Searching for your engine name together with multiline flag or end of string anchor usually finds the exact definition. In editors and online testers, the option is usually labeled multiline or shown as a flag letter m. Some editors always search line by line and have no such toggle. This review did not verify the menus or controls of specific products, so confirm the option in your tool's own documentation.
Bottom line
Use $ with multiline mode when you need to match or insert at the end of every line, and use \z, or $ without multiline in JavaScript, when you mean the end of the whole input. Before relying on a pattern, check the line-ending style of your data, avoid \s when blank lines must survive, and test the final output in the engine where the pattern will actually run. If the task is only about literal line breaks or per-line trimming, a plain-text method is usually simpler and less fragile.