Regex.Replace 替换空匹配
Regex.Replace replaces empty match
我使用以下正则表达式仅替换非空行(有空格的行不算空)。
^(.+)$
使用多行选项。
根据 regex101 这应该有效:https://regex101.com/r/S5Fcqw/1
但似乎 C# 对正则表达式的实现有点不同。我可以用替换来完成这项工作还是需要查看匹配项?
这是调用:Regex.Replace(text, @"^(.+)$", " ", 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}";
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);
}
所以解决方法是不依赖 $
来匹配换行符,而是手动匹配。
我现在使用:@"([^\r\n]+\r?\n?)"
和 RegexOptions.SingleLine
(不确定是否有必要),它对我的用例很有效。
我使用以下正则表达式仅替换非空行(有空格的行不算空)。
^(.+)$
使用多行选项。
根据 regex101 这应该有效:https://regex101.com/r/S5Fcqw/1
但似乎 C# 对正则表达式的实现有点不同。我可以用替换来完成这项工作还是需要查看匹配项?
这是调用:Regex.Replace(text, @"^(.+)$", " ", 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}";
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);
}
所以解决方法是不依赖 $
来匹配换行符,而是手动匹配。
我现在使用:@"([^\r\n]+\r?\n?)"
和 RegexOptions.SingleLine
(不确定是否有必要),它对我的用例很有效。