2012-04-19 68 views
0

有(及以上.NET 3.5)已经是一个方法拆分像这样的字符串:SplitString或SubString或?

  • 字符串str = “{} myvalue的别的东西{} MyOtherValue”
  • 结果:myvalue的,MyOtherValue
+0

你想括号内抢占位符? – 2012-04-19 14:25:19

+6

使用正则表达式类。 – 2012-04-19 14:26:00

+0

是的,我想获取大括号内的值(代表字符串)。 – user1011394 2012-04-19 14:27:00

回答

2

不喜欢:

 string regularExpressionPattern = @"\{(.*?)\}"; 
     Regex re = new Regex(regularExpressionPattern); 
     foreach (Match m in re.Matches(inputText)) 
     { 
      Console.WriteLine(m.Value); 
     } 
     System.Console.ReadLine(); 

不要忘记添加新的命名空间:System.Text.RegularExpressions;

+0

thx添加linl布拉德:) – 2012-04-19 14:40:38

+0

最初去拼写“Expressins”,但后来认为OP的参考是有用的。 ;-) – 2012-04-19 14:42:28

2

您可以使用正则表达式来做到这一点。该片段打印MyValueMyOtherValue

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); 
} 
1

事情是这样的:

string []result = "{MyValue} something else {MyOtherValue}". 
      Split(new char[]{'{','}'}, StringSplitOptions.RemoveEmptyEntries) 

string myValue = result[0]; 
string myOtherValue = result[2]; 
+0

我相信你正在寻找索引['0'&'2'](http://ideone.com/GNXzW)而不是'0'和'1'。 – 2012-04-19 14:41:00

+0

@BradChristie:对,已更正。谢谢。只是错字... – Tigran 2012-04-19 14:42:14

1
MatchCollection match = Regex.Matches(str, @"\{([A-Za-z0-9\-]+)\}", RegexOptions.IgnoreCase); 
Console.WriteLine(match[0] + "," + match[1]);