簡體   English   中英

如何在C#中使用Regex對字符串進行空格填充?

[英]How to space pad a string using Regex in C#?

我有以下格式的多個字符串“ (space)> sometext > anothertext ”。

sometext ”和“ anothertext ”可以是任何東西-他們可以在長度和內容各不相同。

每個字符串的前綴始終是“ (space)> ”,而(space)是任意給定數量的空格字符,直到給定最大長度為止。

例子:

前綴長度上限為10。

 1. "> here is same 1 > sample 1"
 2. "  > here is sample 2 > sample 2 indeed"
 3. "     > a very long spaced prefix > spaced prefix"

我需要將所有前綴對齊到相同的空間長度。 例如,將所有字符對齊10個空格 ...

 1. "          > here is same 1 > sample 1"
 2. "          > here is sample 2 > sample 2 indeed"
 3. "          > a very long spaced prefix > spaced prefix"

我正在使用Regex通過以下代碼實現此目標:

int padding = 10;
Regex prefix = new Regex(@"^(\s*)>.*");
Match prefix_match = prefix.Match(line);
if (prefix_match.Success == true)
{
    string space_padding = new string(' ', padding - prefix_match.Groups[1].Value.Length);
    return prefix.Replace(line, space_padding);
}
return line;

但是我總是得到的結果是10個空格長度的字符串...

這將起作用。

string text = "   > a very long spaced prefix > spaced prefix";
text = "          " + text.Trim();

或者,您可以使用:

string text = "     > a very long spaced prefix > spaced prefix";
text = new String(' ', 10) + text.Trim();

您可以結合使用TrimString構造函數:

string text =  "     > a very long spaced prefix > spaced prefix";
text = new string(' ', 10) + text.Trim();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM