我正在尝试编写一个正则表达式,以删除所有这样的前导空格:
以下代码可以做到这一点,但也可以贪婪地删除多行,如下所示:
如何更改正则表达式,以便它从每行中删除前面的空格,但保持多行不变?
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace test_regex_double_line
{
class Program
{
static void Main(string[] args)
{
List<string> resources = new List<string>();
resources.Add("Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.");
foreach (var resource in resources)
{
var fixedResource = Regex.Replace(resource, @"^\s+", m => "", RegexOptions.Multiline);
Console.WriteLine($"{resource}\n--------------\n{fixedResource}\n===========================");
}
}
}
}
答案 0 :(得分:2)
让我们尝试删除所有空白 (\s
)但是 \n
和\r
,即[\s-[\r\n]]+
模式
代码:
string resource =
"Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.";
string fixedResource = Regex.Replace(resource, @"^[\s-[\r\n]]+", "", RegexOptions.Multiline);
Console.Write(fixedResource);
结果:
Jim Smith
123 Main St.
Wherever, ST 99999
First line of information.
Second line of information.
编辑::如果要处理集合(例如List<string>
),则可以在外部定义Regex
em>出于性能原因的循环(Linq)等(请参见Panagiotis Kanavos评论):
List<string> resources = new List<string>() {
"Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.",
};
Regex regex = new Regex(@"^[\s-[\r\n]]+", RegexOptions.Multiline);
List<string> fixedResources = resources
.Select(resource => regex.Replace(resource, ""))
.ToList();