c# - 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);
}
}
解决方案
.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# 演示。
推荐阅读
- watchos - 我是否错过了从 watchOS 中获取数据的其他方法?
- javascript - 为什么在使用计算属性时不能在 v-if 中的字符串上使用 .includes?
- performance - 如何解释 UWP Store App 的 Visual Studio 2019 性能配置文件
- node.js - 如何将变量传递给 page.on('dialog')?
- mysql - 有什么方法可以为 SQL 中的函数分配名称,以便以后引用?
- css - 上次更新中的 Chrome 开发者工具的麻烦错误。我怎样才能避免它?
- java - 我想更新其中包含双引号和分号的字符串数据
- splunk - 表格,打印每个选定字段的行数
- python - 合并具有相同ID但不同序列号的行
- excel - sumproduct sumifs - 公式在 excel 中有效,不在谷歌表格中