[英]Regex.Replace generates a space in the LinqPad output window out of nowhere
我正在編寫一個腳本來幫助我將一組文本文件轉換為markdown。 該腳本要做的事情之一是對圖形標題應用斜體和標題格式,圖形標題是以一些空格和單詞“ 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);
}
}
的.
.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#演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.