0

Shown below is a simple function, which was run in the middle of a text file that contained multiple instances of repeated blank lines. The output of the function is also shown below.

The only difference between my-search-string-1 and my-search-string-2 is the use of ..\n.. in the first string and ..\\n.. in the second. Since a tab character has to be escaped via ..\\t.., why doesn't the newline character have to be escaped via ..\\n..?

(defun my-find-consecutive-blank-lines ()    
    "re-search-forward two or more consecutive blank lines."
    (interactive)
    (setq my-search-string-1 "\\(^\\(\\t\\| \\)*\n\\)\\{2,\\}")
    (setq my-search-string-2 "\\(^\\(\\t\\| \\)*\\n\\)\\{2,\\}")
    (if (re-search-forward my-search-string-1 nil t)
        (print "my-search-string-1 Found")
    ;;else
        (print "my-search-string-1 Not Found"))
    (if (re-search-forward my-search-string-2 nil t)
        (print "my-search-string-2 Found")
    ;;else
        (print "my-search-string-2 Not Found"))
    (makunbound 'my-search-string-1)
    (makunbound 'my-search-string-2))

"my-search-string-1 Found"
"my-search-string-2 Not Found"
2

Newline and tab are both escaped with a single backslash, because they are escape sequences for the read syntax for strings, and not escape sequences for regular expression syntax.

Those characters have no escape sequences in regular expression syntax at all -- they must appear literally in the pattern.

In double-quoted strings, however, you can use "\n" and "\t" (which is putting a literal newline/tab into the string object produced by the lisp reader, and hence into the regexp).

The double \\ escaping in double-quoted regexps in general is because backslash is special to both strings and regexps, so if you want the backslash to appear in the regexp you need to escape it for the string read syntax.

Using a double-backslash with "\\n" and "\\t" you are therefore passing \n and \t through to the regular expression, where they are treated as simple n and t respectively, because \n and \t aren't special to regexps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.