简体   繁体   English

将多行正则表达式中的字符串替换为行尾令牌

[英]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. 如果我使用\\r\\n ,它可以工作,但我想支持所有类型的换行符。 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). 作为另一个答案陈述我必须使用RegexOptions.Multiline才能使用$作为行结束标记(而不是字符串结尾)。 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 . 它与换行符不匹配,它匹配\\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 这将匹配组合\\n\\r\\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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