Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.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#_.net_String - Fatal编程技术网

C# 如何获取字符串中角括号内的子字符串

C# 如何获取字符串中角括号内的子字符串,c#,.net,string,C#,.net,String,我认为这是一个很愚蠢的问题,但是我不能用一句话来表达那些在棱角分明的巴克茨范围内的观点 var str = "MR. {Name} of {Department} department stood first in {Subjectname}" 我需要获得子字符串(作为数组)这些子字符串位于角度制动器内 like strArray应该包含上述给定字符串中的{Name,Department,Subjectname}List fields=new List(); List<strin

我认为这是一个很愚蠢的问题,但是我不能用一句话来表达那些在棱角分明的巴克茨范围内的观点

var str = "MR. {Name} of {Department} department stood first in {Subjectname}"
我需要获得子字符串(作为数组)这些子字符串位于角度制动器内

like strArray应该包含上述给定字符串中的{Name,Department,Subjectname}

List fields=new List();
    List<string> fields = new List<string>();
    foreach(Match match in Regex.Matches(str, @"\{([^\}]*)\}")) {
        fields.Add(match.Groups[1].Value);
    }
foreach(Regex.Matches(str,@“\{([^\}]*)\}”)中的匹配){ fields.Add(match.Groups[1].Value); }

或用于格式化(填充空格)-请参见。

使用String.IndexOf(“{”)获取第一个打开标记的索引,使用String.IndexOf(“}”)获取第一个关闭标记的索引。然后使用其他字符串函数将其取出(substring、remove等)…虽然仍有标记

注意到您的问题中使用了
var
,但我假设您使用的是.NET 3.5
下面代码的一行应该可以做到这一点

string[] result = Regex.Matches(str, @"\{([^\}]*)\}").Cast<Match>().Select(o => o.Value).ToArray();
string[]result=Regex.Matches(str,@“\{([^\}]*)\}”).Cast().Select(o=>o.Value.ToArray();

是的,这要省力得多