如何在c#中替换字符串中的换行符?
我会使用环境。当我想为字符串插入换行符,而不是从字符串中删除所有换行符时,使用换行符。
根据不同的平台,你可以使用不同类型的换行符,但即使在同一个平台中,也经常使用不同类型的换行符。特别是在处理文件格式和协议时。
string ReplaceNewlines(string blockOfText, string replaceWith)
{
return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}
扩展The.Anyi。9的答案,你也应该知道一般使用的不同类型的换行符。根据文件的来源,您可能希望确保捕获所有替代选项…
string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
应该能让你继续…
将replace替换为Environment。换行符
myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;
正如在其他文章中提到的,如果字符串来自另一个环境(OS),那么您需要替换特定环境的新行控制字符实现。
如果您的代码应该在不同的环境中运行,我会考虑使用Environment。NewLine常量,因为它是特定环境中使用的换行符。
line = line.Replace(Environment.NewLine, "newLineReplacement");
但是,如果您从另一个系统上的文件中获取文本,这可能不是正确的答案,您应该替换为在另一个系统上使用的任何换行常数。它通常是\n或\r\n。
不要忘记replace不会在字符串中进行替换,而是返回一个替换了字符的新字符串。下面将删除换行符(而不是替换它们)。如果用其他方法替换它们,我将使用@Brian R. Bondy的方法,可能包装为扩展方法。记住,在调用Replace或提供的扩展方法之前,首先检查空值。
string line = ...
line = line.Replace( "\r", "").Replace( "\n", "" );
作为扩展方法:
public static class StringExtensions
{
public static string RemoveLineBreaks( this string lines )
{
return lines.Replace( "\r", "").Replace( "\n", "" );
}
public static string ReplaceLineBreaks( this string lines, string replacement )
{
return lines.Replace( "\r\n", replacement )
.Replace( "\r", replacement )
.Replace( "\n", replacement );
}
}
string s = Regex.Replace(source_string, "\n", "\r\n");
or
string s = Regex.Replace(source_string, "\r\n", "\n");
这取决于你想走哪条路。
希望能有所帮助。
安全替换换行符的最好方法是
yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n") //handling mac linebreaks
这将产生一个只有\n(如换行)作为换行符的字符串。 这段代码对于修复混合换行也很有用。
我需要将\r\n替换为实际的回车和换行,并将\t替换为实际的制表符。所以我想到了以下几点:
public string Transform(string data)
{
string result = data;
char cr = (char)13;
char lf = (char)10;
char tab = (char)9;
result = result.Replace("\\r", cr.ToString());
result = result.Replace("\\n", lf.ToString());
result = result.Replace("\\t", tab.ToString());
return result;
}
到目前为止发布的解决方案要么只替代Environment。如果替换字符串包含换行符,则会失败,因为它们调用string。多次替换。
下面是一个解决方案,它使用正则表达式在一次字符串传递中完成所有三个替换。这意味着替换字符串可以安全地包含换行符。
string result = Regex.Replace(input, @"\r\n?|\n", replacementString);
由于新行可以用\n, \r和\r\n来分隔,首先我们将\r和\r\n替换为\n,然后才分割数据字符串。
下面的代码行应该进入parseCSV方法:
function parseCSV(data) {
//alert(data);
//replace UNIX new lines
data = data.replace(/\r\n/g, "\n");
//replace MAC new lines
data = data.replace(/\r/g, "\n");
//split into rows
var rows = data.split("\n");
}
为了确保所有可能的换行方式(Windows, Mac和Unix)都被替换,您应该使用:
string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');
按照这个顺序,当你发现一些行尾字符的组合时,不要使用额外的换行符。
为什么不是两者都有呢?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
注意:用输入字符串的名称替换string。
另一种选择是在有问题的字符串上创建一个StringReader。在读取器上,循环执行. readline()。然后你将直线分开,不管它们有什么(一致的或不一致的)分隔符。有了这些,你就可以随心所欲了;一种可能是使用StringBuilder并在其上调用. appendline。
这样做的好处是,可以让框架决定什么是“换行符”。
如果你想“清除”新行,flamebaud注释使用regex @“[\r\n]+”是最好的选择。
using System;
using System.Text.RegularExpressions;
class MainClass {
public static void Main (string[] args) {
string str = "AAA\r\nBBB\r\n\r\n\r\nCCC\r\r\rDDD\n\n\nEEE";
Console.WriteLine (str.Replace(System.Environment.NewLine, "-"));
/* Result:
AAA
-BBB
-
-
-CCC
DDD---EEE
*/
Console.WriteLine (Regex.Replace(str, @"\r\n?|\n", "-"));
// Result:
// AAA-BBB---CCC---DDD---EEE
Console.WriteLine (Regex.Replace(str, @"[\r\n]+", "-"));
// Result:
// AAA-BBB-CCC-DDD-EEE
}
}
如果你只想替换换行符:
var input = @"sdfhlu \r\n sdkuidfs\r\ndfgdgfd";
var match = @"[\\ ]+";
var replaceWith = " ";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input.Replace(@"\n", replaceWith).Replace(@"\r", replaceWith), match, replaceWith);
Console.WriteLine("output: " + x);
如果你想替换换行符,制表符和空格:
var input = @"sdfhlusdkuidfs\r\ndfgdgfd";
var match = @"[\\s]+";
var replaceWith = "";
Console.WriteLine("input: " + input);
var x = Regex.Replace(input, match, replaceWith);
Console.WriteLine("output: " + x);
基于@mark-bayers的答案和更清晰的输出:
string result = Regex.Replace(ex.Message, @"(\r\n?|\r?\n)+", "replacement text");
它删除了\r\n, \n和\r,而偏爱较长的一个,并将多次出现简化为一次。
使用。net 6中的new方法
myString = myString.ReplaceLineEndings();
替换当前字符串中的所有换行序列。
文档: ReplaceLineEndings
这是一个非常冗长的单行解决方案,但它是我发现的唯一一个工作,如果你不能使用特殊字符转义,如“\r”和“\n”和\x0d和\u000D以及System.Environment.NewLine作为参数的replace()方法
MyStr.replace( System.String.Concat( System.Char.ConvertFromUtf32(13).ToString(), System.Char.ConvertFromUtf32(10).ToString() ), ReplacementString );
这有点离题了,但是为了让它在Visual Studio的XML .props文件中工作,这些文件通过XML属性调用. net,我必须像下面所示那样对它进行修饰。 Visual Studio XML—> . net环境只是不接受特殊字符转义,如“\r”和“\n”以及\x0d和\u000D以及System.Environment.NewLine作为replace()方法的参数。
$([System.IO.File]::ReadAllText('MyFile.txt').replace( $([System.String]::Concat($([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString()))),$([System.String]::Concat('^',$([System.Char]::ConvertFromUtf32(13).ToString()),$([System.Char]::ConvertFromUtf32(10).ToString())))))
推荐文章
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 将整数转换为字符串,以逗号表示千
- 转换为值类型'Int32'失败,因为物化值为空
- 将JavaScript字符串中的多个空格替换为单个空格
- c#中有任何连接字符串解析器吗?
- printf()和puts()在C语言中的区别是什么?
- 在Linq中转换int到字符串到实体的问题
- 是否可以动态编译和执行c#代码片段?
- 创建自定义MSBuild任务时,如何从c#代码获取当前项目目录?
- MSBuild路径
- c#和Java的主要区别是什么?
- 在c#中创建一个特定时区的DateTime
- .NET中的属性是什么?
- csproj文件中的“Service Include”是干什么用的?