用于查找 LF 行结尾并将其修复为 CRLF 的正则表达式

Regex to find and fix LF lineEndings to CRLF

Similar/Related 至,但未涵盖:


我主要在 .NET 堆栈中工作,我们希望(几乎)所有文件都是 CRLF。

在我看来,git 永远不应该编辑文件的内容,所以我和我的项目以及我的同事的 git 设置是 autocrlf=false(即 as-is, as-is), 欢迎就 some other question 进行辩论:)

偶尔有人会有错误的 git 设置,或者以其他方式不小心将 LF 引入 git 存储库中的某些文件,我想 grep 整个存储库以查找带有 LF 行的文件-endings,然后逐个文件将它们修复为 CRLF(以防万一 bash 文件 应该 遗憾地是 LF)。

每次我需要这样做,我都找不到相关的正则表达式,不得不从头开始。

所以这个问题的存在是为了记录正确的正则表达式。

正则表达式查找不属于 CRLF 的任何 LF:

(?<!\r)\n

正则表达式查找不属于 CRLF 的任何 CR:

\r(?!\n)

因此 Regex 找到 any non-CRLF lineEnding:

((?<!\r)\n|\r(?!\n))

您只需将其替换为 \r\n 即可将它们全部修复为 CRLF


这是使用 "Negative Lookbehind" 功能:

(?<\!a)b matches a "b" that was not preceded by an "a".

和 "Negative Lookahead" 功能:

a(?\!b) matches an "a" that is not followed by a "b".

更多文档在这里:https://www.regular-expressions.info/lookaround.html