是否有(.NET 3.5 及更高版本)已经有一种拆分字符串的方法,如下所示:
- string str = "{MyValue} 其他 {MyOtherValue}"
- 结果: MyValue , MyOtherValue
喜欢:
string regularExpressionPattern = @"\{(.*?)\}";
Regex re = new Regex(regularExpressionPattern);
foreach (Match m in re.Matches(inputText))
{
Console.WriteLine(m.Value);
}
System.Console.ReadLine();
不要忘记添加新的命名空间:System.Text.RegularExpressions;
您可以使用正则表达式来做到这一点。此片段打印MyValue
和MyOtherValue
.
var r = new Regex("{([^}]*)}");
var str = "{MyValue} something else {MyOtherValue}";
foreach (Match g in r.Matches(str)) {
var s = g.Groups[1].ToString();
Console.WriteLine(s);
}
像这样的东西:
string []result = "{MyValue} something else {MyOtherValue}".
Split(new char[]{'{','}'}, StringSplitOptions.RemoveEmptyEntries)
string myValue = result[0];
string myOtherValue = result[2];
MatchCollection match = Regex.Matches(str, @"\{([A-Za-z0-9\-]+)\}", RegexOptions.IgnoreCase);
Console.WriteLine(match[0] + "," + match[1]);