简体   繁体   中英

Replace a string in multiline regex with end of line token

I got the following regex

var fixedString = Regex.Replace(subject, @"(:[\w]+ [\d]+)$", "", 
                                                        RegexOptions.Multiline);

which doesn't work. It works if I use \\r\\n , but I would like to support all types of line breaks. As another answer states I have to use RegexOptions.Multiline to be able to use $ as end of line token (instead of end of string). But it doesn't seem to help.

What am I doing wrong?

I am not sure what you want to achieve, I think I understood, you want to replace also the newline character at the end of the row.

The problem is the $ is a zero width assertion. It does not match the newline character, it matches the position before \\n .

You could do different other things:

  1. If it is OK to match all following newlines, means also all following empty rows, you could do this:

     var fixedString = Regex.Replace(subject, @"(:[\\w]+ [\\d]+)[\\r\\n]+", ""); 
  2. If you only want to match the newline after the row and keep following empty rows, you have to make a pattern for all possible combinations, eg:

     var fixedString = Regex.Replace(subject, @"(:[\\w]+ [\\d]+)\\r?\\n", ""); 

    This would match the combination \\n and \\r\\n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM