Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中使用正则表达式填充字符串的空格?_C#_Regex - Fatal编程技术网

如何在C#中使用正则表达式填充字符串的空格?

如何在C#中使用正则表达式填充字符串的空格?,c#,regex,C#,Regex,我有以下格式的多个字符串“(空格)>sometext>anothertext” “sometext”和“anothertext”可以是任何文本-它们的长度和内容可以不同 每个字符串的前缀始终为“(空格)>”,而(空格)是任意给定数量的空格字符,直到给定的最大长度 示例: 最大前缀长度为10 1. "> here is same 1 > sample 1" 2. " > here is sample 2 > sample 2 indeed" 3. " >

我有以下格式的多个字符串“
(空格)>sometext>anothertext

sometext
”和“
anothertext
”可以是任何文本-它们的长度和内容可以不同

每个字符串的前缀始终为“
(空格)>
”,而
(空格)
是任意给定数量的空格字符,直到给定的最大长度

示例:

最大前缀长度为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空格长的字符串…

您可以使用
Trim
string
构造函数的组合:

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

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

只要
string.Trim()
并添加空格,正则表达式似乎过于复杂了this@TheGeneral:我很尴尬:)。。。为什么我一开始就想到Regex。谢谢有时候保持简单是非常正确的;)否。PadLeft的参数是字符串的总长度。在该示例中,它不会添加任何空格。PadLeft(10)添加前导空格,直到总长度为10或更多。这是本周我第二次遇到对StackOverflow上PadLeft的误解。@Palldue:谢谢,我改变了答案。