Insert a Newline Character using Regex Replace

。_饼干妹妹 提交于 2019-12-25 18:40:55

问题


I am trying to insert a newline character using a regex replace like so:

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"
)

but I end up with (literally) word\nword rather than an actual newline.

What am I doing wrong?


回答1:


By using the @"" string literal for the replacement string, you're disabling the escape character parsing. If you make the change to the second string to be a normal string, since you don't have any \ characters you need to maintain, it'll work as you're expecting.

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");


来源:https://stackoverflow.com/questions/38407323/insert-a-newline-character-using-regex-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!