【问题标题】:Insert a Newline Character using Regex Replace使用正则表达式替换插入换行符
【发布时间】:2016-07-16 03:08:12
【问题描述】:

我正在尝试使用正则表达式替换插入换行符,如下所示:

strFile = Regex.Replace(
    strFile,
    @"(FA|BO)\s+(\d{3}-\d+)(\s+)(.*?)(\s+)(\d+,*\d*\.\d+)\s*(FA|BO)\s+(\d{3}-\d+)(\s+)(.*?)(\s+)(\d+,*\d*\.\d+)\s*",
    @"$2&$4&$6\n$8&$10&$12"
)

但我最终得到(字面意思)word\nword,而不是实际的换行符。

我做错了什么?

【问题讨论】:

  • 您是否尝试删除@
  • 怎么样,真的不明白如果我删除 arroba 然后我可以使用换行符 \n
  • 当我替换这个没有得到 newlinw 只得到文字 \n

标签: c# regex replace


【解决方案1】:

通过使用@"" 字符串文字作为替换字符串,您将禁用转义字符解析。如果您将第二个字符串更改为普通字符串,因为您没有任何需要维护的 \ 字符,它会按您的预期工作。

strFile = Regex.Replace(
    strFile, 
    @"(FA|BO)\s+(\d{3}-\d+)(\s+)(.*?)(\s+)(\d+,*\d*\.\d+)\s*(FA|BO)\s+(\d{3}-\d+)(\s+)(.*?)(\s+)(\d+,*\d*\.\d+)\s*",
    "$2&$4&$6\n$8&$10&$12");

【讨论】:

  • 我现在明白了,但我忽略了字符 \r
  • @jhonny625 - 请参阅MSDN C# string Reference中的“逐字字符串文字”
猜你喜欢
  • 1970-01-01
  • 2013-01-10
  • 2014-03-10
  • 2019-08-16
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多