c# - 用空字符串替换可变字符串

标签 c# string

我有一个使用 linq-to-XML 读取的 xml 文件。 Linq-to-XML 保留换行符和缩进空格。

所以不要使用这样的 guid:

"FB5417E2-DB15-481d-80D6-D0C4CB26EB1F"

I am getting stuff like this:

"\n    FB5417E2-DB15-481d-80D6-D0C4CB26EB1F"

I have made this method to try and help compensate for this:

public static string ValueTrimmed(this XElement element)
{         
    if (element != null)
        // Remove the newlines and spaces
        return element.Value.Replace("\n      ", "");

    return "";
}

问题是这只适用于 "\n"+ 6 个空格。

有没有办法删除“\n”+任意数量的空格?

注意:在某些情况下,“\n”+ x 空格位于值的内部。
例如:

TextTextTextTextTextTextText\n     TextTextTextTextTextTextText

最佳答案

删除所有后跟空格的换行符:

return Regex.Replace(element.Value, @"\n\s*", String.Empty);

如果你想在行与行之间保留一个空格:

return Regex.Replace(element.Value, @"\n\s*", " ").Trim();

关于c# - 用空字符串替换可变字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3990917/

相关文章:

c# - 是否可以从 .NET 调用 OCaml?

javascript - ES2015 字符串迭代器关于索引的信息

c# - 无法使用 IronPython 导入用 C# 编写的模块

c# - IsMouseOver 对 DockPanel 中的某些元素返回 false

c# - AvalonDock2 : LayoutItemTemplate only for documents

javascript - 如何获得分割字符串 "/"和 "/something"的不同长度

字符串常量的 C# 编译时连接

c++ - 从 std::string 转换为 bool

ruby - 将方括号添加到字符串的第一个字符

c# - 我们什么时候真正需要从重写方法中调用父类的重写方法?