如何替换前导空格但保留多行?

时间:2019-05-31 14:24:32

标签: c# regex

我正在尝试编写一个正则表达式,以删除所有这样的前导空格:

enter image description here

以下代码可以做到这一点,但也可以贪婪地删除多行,如下所示:

enter image description here

如何更改正则表达式,以便它从每行中删除前面的空格,但保持多行不变?

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===========================");
            }
        }
    }
}

1 个答案:

答案 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();