首页 > 解决方案 > Regex.Replace 突然在 LinqPad 输出窗口中生成一个空格

问题描述

我正在编写一个脚本来帮助我将一组文本文件转换为降价。该脚本所做的一件事是将斜体和标题格式应用于图形标题,即以一些空格和单词“Figure”开头的行。这是我的代码:

text = Regex.Replace(text, "^ +(Figure.*)$", "##### _$1_", RegexOptions.Multiline);

如果我用它来转换这个文本:

A Foobar is cool stuff, as we can see in Figure 1.1:

  Figure 1.1  This is a Foobar

More text here.

...然后我明白了:

A Foobar is cool stuff, as we can see in Figure 1.1:

##### _Figure 1.1  This is a Foobar _

More text here.

...这是我想要的,除了一个小细节:在 LinqPad 输出窗口中的最后一个下划线字符之前添加了一个空格。我不知道这是从哪里来的,因为它不存在于原始文本中(在“Foobar”之后有一个 CRLF 序列)。我的正则表达式或我如何使用它有什么问题?

编辑:演示问题的完整可执行程序:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string text =
@"A Foobar is cool stuff, as we can see in Figure 1.1:

  Figure 1.1  This is a Foobar

More text here.";

        text = Regex.Replace(text, "^ +(Figure.*)$", "##### _$1_", RegexOptions.Multiline);
        Console.WriteLine(text);
    }
}

标签: c#.netregex

解决方案


.NET 正则表达式中的.模式匹配 CR 符号。_它位于捕获到第 1 组的文本的末尾,因此您在替换的最后一个之前有一个换行符。根据您的反馈,LinqPad 的输出窗口将 CR 符号替换为“空格”。

替换.[^\r\n]它将匹配除 CR 和 LF 字符之外的任何字符,并删除$,因为不再需要断言行尾(该RegexOptions.Multiline选项仍然是必需的,以便^可以匹配行首):

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        string text = "A Foobar is cool stuff, as we can see in Figure 1.1:\r\n\r\n  Figure 1.1  This is a Foobar\r\n\r\nMore text here.";
        text = Regex.Replace(text, "^ +(Figure[^\r\n]*)", "##### _$1_", RegexOptions.Multiline);
        Console.WriteLine(text);
    }
}

请参阅C# 演示


推荐阅读