2012-04-19 40 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]); 
相關問題