2013-08-29 10 views
0

命名空間或類型的列表這是我的代碼:如何更換使用正則表達式

string _type="System.Collections.Generic.List<PhilpostDB.ViewModel.Person>"; 
_type = Regex.Replace(_type, @"[.\w]+\.(\w+)", "$1"); // this result=List<Person> 

我想結果:_type = PhilpostDB.ViewModel.Person

回答

1

搜索:

[^<]+\<([^>]+)\> 

並將其替換:

$1 

即:

_type = Regex.Replace(_type, @"[^<]+\<([^>]+)\>", "$1"); 
1

應僅處理字符串的方法工作:

string _type = "System.Collections.Generic.List<PhilpostDB.ViewModel.Person>"; 
string[] tokens = _type.Split('<'); 
string result = tokens[0].Split('.').Last(); 
if (tokens.Length > 1) 
{ 
    string token2 = tokens.Last().Split('.').Last(); 
    result = string.Format("{0}<{1}", result, token2); 
} 

Demo

編輯感謝蒂姆,但如果我想結果= PhilpostDB.ViewModel.Person?

string genericType = _type.Split('<').Last().TrimEnd('>'); 
+0

感謝@tim但是如果我想導致= PhilpostDB.ViewModel.Person –