【问题标题】:Regex.Replace replaces empty matchRegex.Replace 替换空匹配
【发布时间】:2021-05-28 16:56:37
【问题描述】:

我使用以下正则表达式仅替换非空行(带空格的行不算为空)。

^(.+)$ 带有多行选项。

根据 regex101 这应该可以工作:https://regex101.com/r/S5Fcqw/1

但似乎 C#s 的正则表达式实现有点不同。我可以使用替换来完成这项工作还是需要查看匹配项?

这是电话:Regex.Replace(text, @"^(.+)$", " $1", RegexOptions.Multiline);

语言是 C# 7.2 和 net472 作为目标框架。

所以我现在找到了有问题的组合:

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

【问题讨论】:

  • 您的正则表达式不匹配。你能显示minimal reproducible example吗?另外,\r\n != \n
  • 我同意。也许用dotnetfiddle.net 设置一个简短的示例如果您可以在此处写下输入和预期输出也会有所帮助。
  • 我一定错过了什么,因为我在结果中看不到问题。 dotnetfiddle.net/WHXVU7。您能否提供和输入导致问题的原因、您得到的结果以及您想要的结果?
  • @CodeCaster 已修复。当我复制那条线时,我正在玩耍。对此感到抱歉。
  • @DragandDrop 你没有错过任何东西。它为你工作。让我检查一下我这边还有什么问题。

标签: c# regexp-replace


【解决方案1】:

所以解决方法是不依赖$ 来匹配换行符,而是手动进行。

我现在使用:@"([^\r\n]+\r?\n?)"RegexOptions.SingleLine(不确定是否有必要),它适用于我的用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多