如何在C#中从字符串中删除"\r\n"?我能使用正则表达式吗?

69

我正在尝试持久化来自ASP.NET文本区域的字符串。我需要去除回车和换行,然后将剩下的内容分成50个字符一组的字符串数组。

到目前为止,我有以下代码:

var commentTxt = new string[] { };
var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox;
if (cmtTb != null)
  commentTxt = cmtTb.Text.Length > 50
      ? new[] {cmtTb.Text.Substring(0, 50), cmtTb.Text.Substring(51)}
      : new[] {cmtTb.Text};

这段代码可以正常工作,但我没有去除文本中的CrLf字符。要正确做到这点,我该怎么做?

9个回答

128

你可以使用正则表达式,但是一个简单的string.Replace()可能就足够了。

 myString = myString.Replace("\r\n", string.Empty);

6
Environment.NewLine 是服务器认为的换行符。这段文本来自客户端,它可能使用不同的字符表示换行符。以下是一个回答,展示了不同浏览器用于表示换行的字符:https://dev59.com/43M_5IYBdhLWcg3w9oIA#1156388 - Matt Greer
4
在它们之间放上一个管道符号,就可以在一行代码中完成它:myString.Replace("\r|\n", string.Empty); - David Lilljegren
2
抱歉,应该是 Regex.Replace(myString, "\n|\r", String.Empty);,这样就可以一次性替换两个了。 - David Lilljegren

62

.Trim()函数会为您完成所有工作!

我正在尝试上面的代码,但是在“trim”函数之后,我注意到它在到达替换代码之前就已经全部“清洁”了!

String input:       "This is an example string.\r\n\r\n"
Trim method result: "This is an example string."

来源:http://www.dotnetperls.com/trim


31
由于这仅适用于字符串的开头和结尾,因此只能起到这方面的作用。 - mellis481
6
我认为给这个帖子点踩有些不必要,我只是发现它并使用了它,对于我的情况来说绝对是最好的选择。 - Sean Missingham
9
仅因为一个不足的回答对您起作用并不意味着它是一个好的回答。 - mellis481

30

将字符串按照任何换行符组合进行拆分,并用空格连接它们,假设您确实希望在换行符的位置使用空格。

var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, @"(?:\r\n|\n|\r)"));
Console.Write(newString);

// prints:
// the quick brown fox jumped over the box and landed on some rocks.

更好的选择...无与伦比! - user330606
谢谢,那节省了我很多时间! - Munchies
这对我最有帮助了。 - OneHoopyFrood
最好的选择,我正是在寻找这个!谢谢。 - user2603796

27

更好的代码:

yourstring = yourstring.Replace(System.Environment.NewLine, string.Empty);

15
只有在相同的环境下创建文本时,这才有效。 - Gabriel McAdams

6

以下是完美的方法:

请注意,Environment.NewLine 仅适用于 Microsoft 平台。

除了上述内容外,您还需要在一个独立的函数中添加\r\n

这里是支持在Linux、Windows或Mac上输入的代码:

var stringTest = "\r Test\nThe Quick\r\n brown fox";

Console.WriteLine("Original is:");
Console.WriteLine(stringTest);
Console.WriteLine("-------------");

stringTest = stringTest.Trim().Replace("\r", string.Empty);
stringTest = stringTest.Trim().Replace("\n", string.Empty);
stringTest = stringTest.Replace(Environment.NewLine, string.Empty);

Console.WriteLine("Output is : ");
Console.WriteLine(stringTest);
Console.ReadLine();

3

试试这个:

private void txtEntry_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            string trimText;

            trimText = this.txtEntry.Text.Replace("\r\n", "").ToString();
            this.txtEntry.Text = trimText;
            btnEnter.PerformClick();
        }
    }

1
使用Replace("\r", "").Replace("\n", "")来支持更广泛的平台特定的行尾序列。 - Stijn Van Antwerpen

0

使用 double \ 或在 " 前使用 @ 来查找 \r 或 \n

htmlStr = htmlStr.Replace("\\r", string.Empty).Replace("\\n", string.Empty);
htmlStr = htmlStr.Replace(@"\r", string.Empty).Replace(@"\n", string.Empty);

0
假设您想要用某些内容替换换行符,使得类似以下的内容:
the quick brown fox\r\n
jumped over the lazy dog\r\n

不要像这样结束:

the quick brown foxjumped over the lazy dog

我会这样做:
string[] SplitIntoChunks(string text, int size)
{
    string[] chunk = new string[(text.Length / size) + 1];
    int chunkIdx = 0;
    for (int offset = 0; offset < text.Length; offset += size)
    {
        chunk[chunkIdx++] = text.Substring(offset, size);
    }
    return chunk;
}    

string[] GetComments()
{
    var cmtTb = GridView1.Rows[rowIndex].FindControl("txtComments") as TextBox; 
    if (cmtTb == null)
    {
        return new string[] {};
    }

    // I assume you don't want to run the text of the two lines together?
    var text = cmtTb.Text.Replace(Environment.Newline, " ");
    return SplitIntoChunks(text, 50);    
}

如果语法不完美,我很抱歉;因为我现在没有可用的C#机器。


0

使用:

string json = "{\r\n \"LOINC_NUM\": \"10362-2\",\r\n}";
var result = JObject.Parse(json.Replace(System.Environment.NewLine, string.Empty));

字符串 json= "{\r\n "LOINC_NUM": "10362-2",\r\n}"; - Ramya Prakash Rout

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接