正则表达式(C#):将\n替换为\r\n [英] Regex (C#): Replace \n with \r\n
问题描述
如何在C#中使用正则表达式将\n的单个实例替换为\r\n(LF仅与CRLF一起使用)?
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?
对不起,如果这是一个愚蠢的问题,我是Regex的新手。
Sorry if it's a stupid question, I'm new to Regex.
我知道使用计划 String.Replace
,例如:
I know to do it using plan String.Replace
, like:
myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");
但是,这是微不足道的,会破坏任何 \r + \r\n
However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).
推荐答案
这样做会吗?
[^\r]\n
基本上,它与以不为'\r'的字符开头的'\n'匹配。
Basically it matches a '\n' that is preceded with a character that is not '\r'.
如果要检测到它行也以单个 \n开头,然后尝试
If you want it to detect lines that start with just a single '\n' as well, then try
([^\r]|$)\n
哪个应该与 \n匹配,但仅与一行的第一个字符或 not 的第一个字符以'\r'
Which says that it should match a '\n' but only those that is the first character of a line or those that are not preceded with '\r'
由于您在重新弄乱行本身的定义, $可能无法很好地工作。但是我认为您应该明白这个想法。
There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.
编辑: credit @Kibbee使用look-ahead显然会更好,因为它不会捕获匹配的前一个字符,也应有助于处理任何边缘情况。因此,这里有一个更好的正则表达式+代码变为:
credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:
myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
这篇关于正则表达式(C#):将\n替换为\r\n的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!