简体   繁体   中英

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

But it seems that C#s implementation of regex is a bit different. 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);

Language is C# 7.2 and net472 as target framework.

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.

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