gpt4 book ai didi

c# - 在特定符号前后插入(单个)空格

转载 作者:太空狗 更新时间:2023-10-30 01:01:19 25 4
gpt4 key购买 nike

我需要在特定符号(例如“|”)前后插入(单个)空格,如下所示:

string input = "|ABC|xyz |123||999|   aaa|   |BBB";
string output = "| ABC | xyz | 123 | | 999 | aaa | | BBB";

这可以使用几个正则表达式模式轻松实现:

string input = "|ABC|xyz |123||999|   aaa|   |BBB";

// add space before |
string pattern = "[a-zA-Z0-9\\s*]*\\|";
string replacement = "$0 ";
string output = Regex.Replace(input, pattern, replacement);

// add space after |
pattern = "\\|[a-zA-Z0-9\\s*]*";
replacement = " $0";
output = Regex.Replace(output, pattern, replacement);

// trim redundant spaces
pattern = "\\s+";
replacement = " ";
output = Regex.Replace(output, pattern, replacement).Trim();

Console.WriteLine("Original String: \"{0}\"", input);
Console.WriteLine("Replacement String: \"{0}\"", output);

但这不是我想要的,我的目标只是使用单一模式。

我尝试了很多方法,但仍然没有达到预期效果。请有人帮我解决这个问题。

提前致谢!

最佳答案

谢谢@Santhosh Nayak。

我只是编写了更多 C# 代码以获得 OP 想要的输出。

string input = "|ABC|xyz |123||999|   aaa|   |BBB";
string pattern = @"[\s]*[|][\s]*";
string replacement = " | ";
string output = Regex.Replace(input, pattern, (match) => {
if(match.Index != 0)
return replacement;
else
return value;
});

我指的是 Regex.Replace(string input, string pattern, MatchEvaluator evaluator)在 MSDN 中。

关于c# - 在特定符号前后插入(单个)空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39864970/

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