我正在编写一个脚本来帮助我将一组文本文件转换为markdown.这个脚本所做的一件事就是将斜体和标题格式应用于图形标题,这些标题是以一些空格和单词"图"开头的行.这是我的代码:
text = Regex.Replace(text, "^ +(Figure.*)$", "##### _$1_", RegexOptions.Multiline);
Run Code Online (Sandbox Code Playgroud)
如果我用它来转换这个文本:
A Foobar is cool stuff, as we can see in Figure 1.1:
Figure 1.1 This is a Foobar
More text here.
Run Code Online (Sandbox Code Playgroud)
...然后我明白了:
A Foobar is cool stuff, as we can see in Figure 1.1:
##### _Figure 1.1 This is a Foobar _
More text here.
Run Code Online (Sandbox Code Playgroud)
...除了一个小细节外,我想要的是:在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);
}
}
Run Code Online (Sandbox Code Playgroud)
..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);
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅C#演示.