简体   繁体   English

Regex.Replace 替换空匹配

[英]Regex.Replace replaces empty match

I'm using the following regex to only replace lines that are not empty (lines with whitespaces do not count as empty).我使用以下正则表达式仅替换非空行(带空格的行不算为空)。

^(.+)$ with the multiline option. ^(.+)$与多行选项。

According to regex101 this should work: https://regex101.com/r/S5Fcqw/1根据 regex101 这应该可以工作: https://regex101.com/r/S5Fcqw/1

But it seems that C#s implementation of regex is a bit different.但似乎 C#s 的正则表达式实现有点不同。 Can I make this work with replace or do I need to look at match?我可以使用替换来完成这项工作还是需要查看匹配项?

This is the call: Regex.Replace(text, @"^(.+)$", " $1", RegexOptions.Multiline);这是调用: Regex.Replace(text, @"^(.+)$", " $1", RegexOptions.Multiline);

Language is C# 7.2 and net472 as target framework.语言为 C# 7.2 和 net472 作为目标框架。

So I have now found the offending combination:所以我现在找到了有问题的组合:

        public static string IndentBy(this string text, int count, string indentationMarker = " ")
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }

            var spaces = string.Join(string.Empty, Enumerable.Repeat(indentationMarker, count));
            var replacement = $"{spaces}$1";
            var indented = Regex.Replace(text, @"^(.+)$", replacement, RegexOptions.Multiline);
            return indented;
        }

        [InlineData("a", "    a")]
        [InlineData("a\nb", "    a\n    b")]
        [InlineData("a\r\nb", "    a\r\n    b")]
        [InlineData("a\n\nb", "    a\n\n    b")]
        [InlineData("a\r\n\r\nb", "    a\r\n\r\n    b")] // this line fails
        public void IndentBy_Input_GivesExpectedOutput(string input, string expected)
        {
            // act
            var indentet = IndentBy(input, 4);

            // assert
            indentet.ShouldBe(expected);
        }

So the fix was to not rely on $ to match the newline but to do it manually.所以解决方法是不依赖$来匹配换行符,而是手动进行。

I use now: @"([^\r\n]+\r?\n?)" with RegexOptions.SingleLine (not sure if necessary) and it works fine for my use-cases.我现在使用: @"([^\r\n]+\r?\n?)"RegexOptions.SingleLine (不确定是否有必要),它适用于我的用例。

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

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