gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:54:17 26 4
gpt4 key购买 nike

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

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

最佳答案

让我们尝试删除所有空格 ( \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 是合理的出于性能原因,在循环 (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();

关于c# - 如何替换前导空格但保留多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56396894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com