有(及以上.NET 3.5)已經是一個方法拆分像這樣的字符串:SplitString或SubString或?
- 字符串str = 「{} myvalue的別的東西{} MyOtherValue」
- 結果:myvalue的,MyOtherValue
有(及以上.NET 3.5)已經是一個方法拆分像這樣的字符串:SplitString或SubString或?
不喜歡:
string regularExpressionPattern = @"\{(.*?)\}";
Regex re = new Regex(regularExpressionPattern);
foreach (Match m in re.Matches(inputText))
{
Console.WriteLine(m.Value);
}
System.Console.ReadLine();
不要忘記添加新的命名空間:System.Text.RegularExpressions;
thx添加linl布拉德:) – 2012-04-19 14:40:38
最初去拼寫「Expressins」,但後來認爲OP的參考是有用的。 ;-) – 2012-04-19 14:42:28
您可以使用正則表達式來做到這一點。該片段打印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];
我相信你正在尋找索引['0'&'2'](http://ideone.com/GNXzW)而不是'0'和'1'。 – 2012-04-19 14:41:00
@BradChristie:對,已更正。謝謝。只是錯字... – Tigran 2012-04-19 14:42:14
MatchCollection match = Regex.Matches(str, @"\{([A-Za-z0-9\-]+)\}", RegexOptions.IgnoreCase);
Console.WriteLine(match[0] + "," + match[1]);
你想括號內搶佔位符? – 2012-04-19 14:25:19
使用正則表達式類。 – 2012-04-19 14:26:00
是的,我想獲取大括號內的值(代表字符串)。 – user1011394 2012-04-19 14:27:00