Insert a Newline Character using Regex Replace

2019-09-19 13:31发布

问题:

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


标签: c# regex replace