You may be interested to see how Ocaml lexer (search and string ) does it. In essence, this is the same method as yours, without a good local buffer (I find your code nicer at this point, but it is a little less efficient), a little more complicated because it supports more screens and uses an escape table (char_for_backslash) to factorize similar rules.
Also, you repeat the "\\n" rule twice, and I think that 1 is a very pessimistic estimate of your string length, I would prefer to use 20 here (to avoid unnecessary resizing).
source share