437 points · by BerislavLopac · 2y ago · 366 comments
Huh. I always think of them as "start-of-line" and "end-of-line". I mean, a lot of the time when I'm working with regexes, I'm working with text a line at a time so the effect is the same, but that doesn't change how I think of those operators.
Maybe because a fair amount of the work I do with regexes (and, probably, how I was introduced to them) is via `grep`, so I'm often thinking of the inputs as "lines" rather than "strings"?
In nearly two decades of using regex I think this might be the first time I've heard of $ being end of string. It's always been end of line for me.
These people are I think not intending to say a newline character is permitted at the end of an e-mail address.
(Of course people using 'grep' would have different expectations for obvious reasons)
I think this series of comments might be clearest: https://news.ycombinator.com/item?id=39764385
> Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.
Or JavaScript:
> An input boundary is the start or end of the string; or, if the m flag is set, the start or end of a line.
\A and \Z are start/end of input regardless of mode… when they’re available, that’s not the case of all engines.
Usually ^ matches only at the beginning of the string, and $ matches only at the end of the string and immediately before the newline (if any) at the end of the string. When this flag is specified, ^ matches at the beginning of the string and at the beginning of each line within the string, immediately following each newline. Similarly, the $ metacharacter matches either at the end of the string and at the end of each line (immediately preceding each newline).
In single-line [2] mode, the line starts at the start of the string and ends at the end of the line where the end of the line is either the end of the string if there is no terminating newline or just before the final newline if there is a terminating newline.
In multi-line mode a new line starts at the start of the string and after each newline and ends before each newline or at the end of the string if the last line has no terminating newline.
The confusion is that people think that they are in string-mode if they are not in multi-line mode but they are not, they are in single-line mode, ^ and $ still use the semantics of lines and a terminating newline, if present, is still not part of the content of the line.
With \n\n\n in single-line mode the non-greedy ^(\n+?)$ will capture only two of the newlines, the third one will be eaten by the $. If you make it greedy ^(\n+)$ will capture all three newlines. So arguably the implementations that do not match cat\n with cat$ are the broken ones.
[1] https://docs.python.org/3/howto/regex.html#more-metacharacte...
[2] I am using single-line to mean not multi-line for convenience even though single-line already has a different meaning.
Only in multiline mode does it match EOL characters, but it does still not appear to consume them. In fact, I cannot construct a regex that captures the last character of one line, then consumes the newline, and then captures the first character of the next line, while using $. The capture group simply ends at $.
Vim is what did that for me.
$ printf 'Line with EOL\nLine without EOL' | grep 'EOL$'
Line with EOL
Line without EOL
$ grep --version | head -n1
grep (GNU grep) 3.8It's not matching the newline character after all.
^ - takes you to start of line $ - takes you to end of line
but yeah seems like a real misunderstanding from “start/end of string” people
String is usually end of line, but not if you use stuff like `N`, to manipulate multi-line strings
Per POSIX chapter 9[1]:
9.2 … "The use of regular expressions is generally associated with text processing. REs (BREs and EREs) operate on text strings; that is, zero or more characters followed by an end-of-string delimiter (typically NUL). Some utilities employing regular expressions limit the processing to lines; that is, zero or more characters followed by a <newline>."
and 9.3.8 … "A <dollar-sign> ( '$' ) shall be an anchor when used as the last character of an entire BRE. The implementation may treat a <dollar-sign> as an anchor when used as the last character of a subexpression. The <dollar-sign> shall anchor the expression (or optionally subexpression) to the end of the string being matched; the <dollar-sign> can be said to match the end-of-string following the last character."
combine to mean that $ may match the end of string OR the end of the line, and it's up to the utility (or mode) to define which. Most of the common utilities (grep, sed, awk, Python, etc) treat it as end of line by default, since they operate on lines by default.
THERE IS NO SINGLE UNIVERSAL REGULAR EXPRESSION SYNTAX. You cannot reliably read or write regular expressions without knowing which language & options are being used.
[1] https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1...
His latest on the topic is cool too: https://www.youtube.com/watch?v=ys7yUyyQA-Y
He's has quite a lot of content that HN folks might be interested in I think, like the reality and woes of consulting[3]
[0] https://www.youtube.com/@RobertElderSoftware
[1] https://blog.robertelder.org/
Today most important bit of information is knowledge that implementations differ and I made a habit of pulling reference sheet for a thing I work with.
E.g. Emacs Regexp annoyingly doesn’t have word in form of “\w” but uses “\s_-“ (or something no reference sheet on screen) as character class (but Emacs has the best documentation and discoverability - a hill I’m willing to die on)
Some utilities require parenthesis escaping and some not. Sometimes this behavior is configurable and sometimes it’s not.
I lived through whole confusion, annoyance, denial phase and now I just accept it. Concept is the same everywhere but flavor changes.
My brain thinks in Perl's regex language and then I have to translate the inconsistent bits to the language I'm using. Especially in the shell - I'm way more likely to just drop a perl into the pipeline instead of trying to remember how sed/grep/awk (GNU or BSD?) prefer their regex.
> Perl is kind of designed to make awk and sed semi-obsolete.
https://pcre.org/current/doc/html/pcre2compat.html
https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expres...
https://stackoverflow.com/questions/70273084/regex-differenc...
Learning Perl today would be a very different experience. I don't think it would catch me as readily as it did back then. But it doesn't matter - it's embedded into me at a deep level because I learned it through a strong drive of fascination and infatuation.
As for the regex themselves? It's powerful and solved a lot of the problems I was trying to solve, was built fundamentally into Perl as a language, so learning it was just an easy iterative process. It didn't hurt that the particular period of time when I learned Perl/regex the community was really big on "leetcode" style exercises, they just happened to be focused around Perl Golf, being clever in how you wrote solutions to arbitrary problems, and abusive levels of regex to solve problems. We were all playing and play is a great way to learn.
Regex, useful in any job...
if you know where to find something no point in knowing it.
Nonsense. And you know it.
First, you need to know what to find, before knowing where to find it. And knowing what to find requires intricate knowledge of the thing. Not intricate implementation details, but enough to point yourself in the right direction.
Secondly, you need to know why to find thing X and not thing Y. If anything, ChatGPT is even worse than google or stackoverflow in "solving the XY problem for you". XY is a problem you don't want solved, but instead to be told that you don't want to solve it.
Maybe some future LLM can also push back. Maybe some future LLM can guide you to the right answer for a problem. But at the current state: nope.
Related: regexes are almost never the best answer to any question. They are available and quick, so all considered, maybe "the best" for this case. But overall: nah.
Here's the explanation for $ in the perlre docs:
$ Match the end of the string
(or before newline at the end of the
string; or before any newline if /m is
used)This is a serious misconception. Perl is far, far from dead. The constant activity of the gargantuan CPAN library more than demonstrates very much the opposite.
I would say Perl and its community has done quite well considering it hasn't had the same mountain of corporate funds thrust into it like more highlighted have. Mainstream ain't everything.
That's one of the benefits of a complete rethink/rewrite, you can learn from the fact that the old behavior surprised people.
It seems so obvious that's the opposite of what they should have defaulted to, that it clearly should have been ^ and $ for lines, and ^^ and $$ for the string, since like ((1)(2)(3)):
^^line1$\n^line2$\n^line3$\n$
[1]: That, and it's not anywhere, while Perl 5 is everywhere.
I feel it's like driving a rental car. It behaves slightly different than your own car, some features missing, some other features added, but in general, most of the things are pretty similar.
So, yes, at least someone (me) considers regex to be standardized in several published de jure standards.
[0] https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf#chapter.28
[1] https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html
[2] https://262.ecma-international.org/14.0/#sec-regexp-regular-expression-objectsA lot of systems implemented PCRE, including JavaScript, since Perl extended the POSIX system with many useful extensions. IIRC, re2 tries to reign in on some of the performance issues and quirks the original systems had, while implementing the whole thing in Go.
edit: Did not realize re2 predated go ...
re2 adds a legitimate option to the menu of using NDFAs, which have the disadvantage of not supporting backreferences, but have the advantage of having constrained complexity of scanning a string. This does not come for free; you can conceivably end up with a compiled regexp of very large size with an NDFA approach, but most of the time you won't. The result may be generally slower than a PCRE-type approach, but it can also end up safer because you can be confident that there isn't a pathological input string for a given regexp that will go exponential.
This is one of those cases where ~99% of the time, it doesn't really matter which you choose, but at the scale of the Entire Programming World, both options need to be available. I've got some security applications where I legitimately prefer the re2 implementation in Go because it is advantageous to be confident that the REs I write have no pathological cases in the arbitrary input they face. PCRE can be necessary in certain high-performance cases, as long as you can be sure you're not going to get that pathological input.
RE engines don't quite engender the same emotions as programming languages as a whole, but this is not cheerleading, this is a sober engineering assessment. I use both styles in my code. I've even got one unlucky exe I've been working with lately that has both, because it rather irreducibly has the requirements for both. Professionally annoying, but not actually a problem.
* Finite automata based regex engines don't necessarily have to be slower than backtracking engines like PCRE. Go's regexp is in practice slower in a lot of cases, but this is more a property of its implementation than its concept. See: https://github.com/BurntSushi/rebar?tab=readme-ov-file#summa... --- Given "sufficient" implementation effort (~several person years of development work), backtrackers and finite automata engines can both perform very well, with one beating the other in some cases but not in others. It depends.
* Fun fact is that if you're iterating over all matches in a haystack (e.g., Go's `FindAll` routines), then you're susceptible to O(m * n^2) search time. This applies to all regex engines that implement some kind of leftmost match priority. See https://github.com/BurntSushi/rebar?tab=readme-ov-file#quadr... for a more detailed elaboration on this point.
Good on you.
I do wonder though what's the highest number of different regex syntaxes I've ever encountered (perhaps written?) within a single line: bash, grep and sed are never not in a "hold my beer" mood!
They seem to improve. Negative lookbehind isn't missing anymore [1]. But still lack the handy \Q and \E to escape stuff [2].
Your comment is missing a trigger warning, lol. But seriously, this is one of my flags for "this should probably be a script, or an awk or perl one-liner."
I've got "hold my beer" commits in .net - I've balanced brackets. I believe that's impossible in sed and grep. If I were going to write a json parser in a script, then a) stop me and b) it's got to be in powershell.
I consider sed to be the baseline. If you can do sed you can do anything but it’s seriously limited.
The regular expression engines available in most mainstream languages go well beyond what is specified in POSIX though. An interesting example is named capturing group in Python, e.g., (?P<token>f[o]+).
Oddly, there are no backreferences in POSIX EREs.
Edit: oh, you mean via regex engines available in GNU tools; I am dumb. Hmm... is there no GNU extension with PCRE?
The semantics of ^ and $ is based on lines - whether single-line or multi-line mode. For string based semantics - which you could also think of as entire file if you are dealing with files - use \A and \Z or their equivalents.
[1] Both interpretations have their merits. If you transmit text over a serial connection, it is useful to have a newline as line terminator so that you know when you received a complete line. If you put text into text files, it might arguably be easier to look at a newline as a line separator because then you can not have a invalid last line. On the other hand having line terminators in text files allows you to detect incompletely written lines.
https://homakov.blogspot.com/2012/05/saferweb-injects-in-var...
> A pattern is a sequence of pattern items. A caret '^' at the beginning of a pattern anchors the match at the beginning of the subject string. A '$' at the end of a pattern anchors the match at the end of the subject string. At other positions, '^' and '$' have no special meaning and represent themselves.
https://www.lua.org/manual/5.3/manual.html#6.4.1
Lua's pattern matching is much simpler than regexes though.
> Unlike several other scripting languages, Lua does not use POSIX regular expressions (regexp) for pattern matching. The main reason for this is size: A typical implementation of POSIX regexp takes more than 4,000 lines of code. This is bigger than all Lua standard libraries together. In comparison, the implementation of pattern matching in Lua has less than 500 lines.
There's an additional caveat: if you use the optional "init" parameter to specify an offset into the string to start matching, the ^ anchor will match at that offset, which may or may not be what you expect.
I find it hard to imagine any other expectation passing the rubber duck test.
"Oh, so you expected the match to always fail, no matter what the string was?"
Don't get me wrong, it's certainly far more useful as it is, I'm glad it works this way.
In raku (aka perl6) Regexes were reinvented by Larry Wall (the creator of perl which made perlRE the de facto regex standard)
Here's what he does with $:
(https://docs.raku.org/language/regexes#Start_of_string_and_e...)
* The $ anchor only matches at the end of the string
* The $$ anchor matches at the end of a logical line. That is, before a newline character, or at the end of the string when the last character is not a newline character.
>>> import re
>>> bool(re.search('abc$', 'abc'))
True
>>> bool(re.search('abc$', 'abc\n'))
True
>>> bool(re.search('abc$', 'abc\n\n'))
False
>>> bool(re.search('abc$', 'abc '))
False
>>> bool(re.search('abc$', 'abc\t'))
False
>>> bool(re.search('abc$', 'abc\r'))
False
>>> bool(re.search('abc$', 'abc\r\n'))
False unless person_id =~ /^\d+$/
abort "Bad person ID"
end
sql = "select * from people where person_id = #{person_id}"
In addition to injection attacks, this also can bite people when parsing headers, where a bad header is allowed to sneak past a filter.https://devcraft.io/2021/05/04/exiftool-arbitrary-code-execu...
$ ruby -e 'x = "25" ; if x =~ /^\d+$/ ; puts "yes" ; else ; puts "no" ; end'
yes
$ ruby -e 'x = "25\n" ; if x =~ /^\d+$/ ; puts "yes" ; else ; puts "no" ; end'
yes
$ ruby -e 'x = "a25\n" ; if x =~ /^\d+$/ ; puts "yes" ; else ; puts "no" ; end'
no
Also, you'd want to use something that parameterizes the query with '?' (I use the Sequel gem) instead of just stuffing it into a sql string.The second line should always be no, which if you use `\A\d+\z`, it will be.
ruby -e 'x = "a\n25\n" ; if x =~ /^\d+$/ ; puts "yes" ; else ; puts "no" ; end'
yes
Good to know. $ ruby -e 'x = "25\n; delete from people" ; if x =~ /^\d+$/ ; puts "yes" ; else ; puts "no" ; end'
yeshttps://www.postgresql.org/docs/current/functions-matching.h...
my $string = "cat\n";
/cat$/s -> true
/cat\Z/s -> true
/cat\z/s -> falseThe end of line character is usually the standard Windows \r\n.
Yes, that means if you want to really match the end of line you have to match "\r$". So broken.
And if you believe \r\n is the way to go, please make sure \n\r also works as they should have the same results. (or \r\n\r\r\r\r for that matter)
\r - returned teletype head to the start of a line
\n - move paper one line down
> The sequence CR+LF was commonly used on many early computer systems that had adopted Teletype machines—typically a Teletype Model 33 ASR—as a console device, because this sequence was required to position those printers at the start of a new line. The separation of newline into two functions concealed the fact that the print head could not return from the far right to the beginning of the next line in time to print the next character. Any character printed after a CR would often print as a smudge in the middle of the page while the print head was still moving the carriage back to the first position. "The solution was to make the newline two characters: CR to move the carriage to column one, and LF to move the paper up."[2] In fact, it was often necessary to send extra padding characters—extraneous CRs or NULs—which are ignored but give the print head time to move to the left margin. Many early video displays also required multiple character times to scroll the display.
Line Feed (\n) - move down 1 line
Essentially, when you're sending commands to teletypes, that's how you'd have to do it.
(For example, most text-based internet protocols such as HTTP use \r\n as a line separator/terminator, so refusing to put the \r will be incompatible for no reason.)
I bet if someday VS Code's Windows build ships with LF default on new installations, people won't even notice.
I mean, at some point it did matter what the OS did when you pressed the "Enter" button. But this isn't really the case much anymore. VS Code catches that keypress, and inserts whatever "files.eol" is set to. Sublime does the same. I didn't check, but I assume every other IDE has this setting.
Similarly, the HTML spec, which is pretty nuts, makes browsers normalize my enters to LF characters as I type into this textarea here (I can check by reading the `value` property in devtools), but when it's submitted, it converts every LF to a CRLF because that's how HTML forms were once specced back in the day. Again though, what my OS considers to be "the standard newline" is simply not considered at all. Even CMD.EXE batch files support LF.
I don't really type newlines all that much outside IDEs and browsers (incl electron apps) and places like MS Word, all of which disregard what the OS does and insert their own thing. Maybe the terminal? I don't even know. I doubt it's very consequential.
EDIT: PSA the same holds for backslashes! Do Not Use Backslashes. Don't use "OS specific directory separator constants". It's not 1998, just type "/" - it just works.
As with '/', they really ought to do this some day but won't.
I don't know if it is the case on Windows 11, but I have surely been bitten by CMD batch files using LF line endings. I don't remember the exact issue but it may have been the one bug affecting labels. [1]
[1]: https://www.dostips.com/forum/viewtopic.php?t=8988#p58888
The rationale was probably "it should be easier to match input strings" and now it's harder for everyone.
Brad Freidl's Mastering Regular Expressions is a good book to read if you want to stop being surprised/lost.
I'll admit I stopped at the dive into DFA/NFA engine details.
Has anyone confirmed this behaviour directly against the runtimes/languages? Newlines at the end of a string are certainly something that could get lost in transit inside an online service involving multiple runtimes.
Beyond what's in the OP, that includes RE2, Hyperscan, D's std.regex, ICU, Perl, Python's third party `regex` package, and `regress`.
I've also run that locally against "go1.22.1 darwin/arm64", "go1.21.5 windows/amd64", and "go1.21.0 linux/amd64" with the same result.
> The ^ and $ language elements indicate the beginning and end of the input string. The end of the input string can be a trailing newline \n character.
In what way could newlines at the end of a string "could get lost in transit"?
There are plenty of other ways, too; bugs happen.
Matching EOL feels natural for every line-based process.
What I find way more annoying is escaping characters and writing character groups. Why can't all regex engines support '\d' and '\w' and such? Why, in sed, is an unescaped '.' a regex-dot matching any character, but an unescaped '(' is just a regular bracket?
It is because sed predates the very influential second generation Extended Regular Expression engine and by default uses the first generation Basic Regular Expression engine. So really it is for backwards compatibility.
http://man.openbsd.org/re_format#BASIC_REGULAR_EXPRESSIONS
you can usually pass sed a -r flag to get it to use ERE's
Actually I don't really know if BRE's predate ERE's or not. I assume they do based on the name but I might be wrong.
The work originally came from work by Stephen Cole Kleene in the 1950s. It was introduced into Unix fame via the QED editor (which later became ed (and sed), then ex, then vi, then vim; all with differing authors) when Ken Thompson added regex when he ported QED to CTSS (an OS developed at MIT for the IBM 709, which was later used to develop Multics, and hence lead to Unix).
Also the "grep" command got its name from "ed"; "g" (the global ed command) "re" (regular expression), and "p" (the print ed command). Try it in vi/vim, :g/string/p it is the same thing as the grep command.
for portability, -E is the POSIX flag for the same thing
My reasoning would be if the file is transmitted and gets truncated nobody would know for sure if it does not end a new line. Brownie points if this is code end has a comment that the files ends there.
The article calls computer languages platforms but the are computer languages. Bash is not included. Weird. I believe the most common use of regular expressions is the use of grep or egrep with bash or some other shell but, who knows. Maybe I am hanging with the wrong crowd.
- The JS/Go/Rust family, which treats $ like \z and does not support \Z at all
- The Java, .NET, PHP, Python family, which treats $ like \Z and may or may not (Python) support \z.
\Z does away with \n before the end of the string, while \z treats \n as a regular character. For multiline $ the distinction doesn't matter, because \n is the end.
Really the only deviation from the rule is Python's \Z, which is indeed weird.
As long as sharing anecdata, in 30 years, it's almost the only way I use it.
It's incredible for slicing and dicing repetitious text into structure. You generally want some sort of Practical Extraction and Reporting Language, the core of which is something like a regular expression, generally able to handle the, well, irregularity.
Most recent example (I did this last week) was extracting Apple's app store purchases from an OCR of the purchase history available through Apple's Music app's Account page that lets you see all purchases across all digital offerings, but only as a long scrolling dialog box (reading that dialog's contents through accessibility hooks only retrieves the first few pages, unfortunately).
Each purchase contains one or more items and each item has one or more vertical lines, and if logos contain text they add arbitrary lines per logo.
A good match and sub match multi-line regex folds that mess back into a CSV. In this case, the regex for this was less than an 80 char line of code and worked in the find replace of Sublime Text which has multiline matching, subgroups, and back references.
Another way to do this is something like a state match/case machine, but why write a program when you can just write a regular expression?
They go only on the tokenizer, if they go somewhere at all.
(/m enables multiline mode)
It must be some kind of philosophical objection because there's no way something with as much water under the bridge as Python simply hasn't got around to it.
> So if you're trying to match a string without a newline at the end, you can't
only use $ in Python! My expectation was having multiline mode disabled
wouldn't have had this newline-matching behavior, but that isn't the case.
I would argue this is correct behavior, a "line" isn't a "line" if it doesn't end with \n.[1] > 3.206 Line - A sequence of zero or more non- <newline> characters plus a terminating <newline> character.
[1] https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1...$ man pcre2syntax
Where you'll find the following block under ANCHORS AND SIMPLE ASSERTIONS:
$ end of subject
also before newline at end of subject
also before internal newline in multiline mode
So all the cases of "newline at/before end of subject" are covered here. Then, the question becomes "what is a subject?" Is it line-by-line? Are newlines included? What if we want multiline matching? That's where re.MULTILINE comes from, it's not "multiline matching" (sort of) it's "what is the subject of the regular expression that we're matching against"The other results that differ across engines seem to be because people either don't understand regex or because the POSIX description of how to deal with such an input and config was ill-defined.
I'm not too surprised by PHP and Python getting it wrong. Java and C# is a slight surprise though.
The real issue is that no language nowadays "just" implements BRE or ERE since both specs are lacking in features.
Most languages instead implement some variant of Perl's regex instead (often called PCRE regex because of the C library that brought Perl's regex to C), which as far as I can tell isn't standardized, so you get these subtle differences between implementations.
A reproducible example would be nice. I don’t understand what it is he cannot do. `re.search('$', 'no new lines')` returns a match.
re.match('^bob$', 'bob\n')
I didn't want the trailing newline to be included.
re.match('^bob$', 'bobs') → no
Most people would expect 'bob\n' not to match, because I used '$' and it has an extra character at the end, just like 'bobs'. In Python it does match because '\n' is a special case.
This, in a nutshell, is the sort of problem which renders fallacious the notion that you can unit-test your way to correct software.
Here’s an interesting project for typed regular expressions: https://news.ycombinator.com/item?id=12292389
``` re.match(text).extract().rstrip(“\n”) ```
The new line is just empty but not the first line anymore.
3.195 Incomplete Line
A sequence of one or more non-<newline> characters at the end of the file.
3.206 Line
A sequence of zero or more non-<newline> characters plus a terminating <newline> character.
courtesy of [0]. See also [1] for rationale on "text file": Text File
[...] The definition of "text file" has caused controversy. The only difference between text and binary files is that text files have lines of less than {LINE_MAX} bytes, with no NUL characters, each terminated by a <newline>. The definition allows a file with a single <newline>, or a totally empty file, to be called a text file. If a file ends with an incomplete line it is not strictly a text file by this definition. [...]
[0] https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1...[1] https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd...
- VSCODE
- Visual Studio
- Notepad
C/C++ compilers that process "incomplete lines"
All of them.
Will my users consider it a bug if my program doesn't process "incomplete lines": Yes. (Yes, I have had this bug logged
against code that I wrote).
Will I consider it a bug if your program doesn't process "incomplete lines": Yes.Note that all of those three apps come from the Windows world where CRLF was indeed a line separator, and a file ending with CRLF was considered to have an empty line at the end.
But yes, you absolutely should accommodate for incomplete lines.
"cat$" with multiline enabled
"cat$" with multiline disabled
"cat\z"
"cat\Z"no matches
PSA: Regex security is particular to each implementation flavor. Please know the nuances of a particular kind and be unambiguously precise.
$ does not mean end of string in Python.