2013-02-14 47 views
5

串我有这样一个字符串列表:C#获取与特定的模式从字符串

List<string> list = new List<string>(); 
list.Add("Item 1: #item1#"); 
list.Add("Item 2: #item2#"); 
list.Add("Item 3: #item3#"); 

我怎样才能获得并添加子#物品1#,##ITEM2等进入一个新的列表?

我只能够获得完整的字符串,如果它包含一个“#”通过这样做:

foreach (var item in list) 
{ 
    if(item.Contains("#")) 
    { 
     //Add item to new list 
    } 
} 
+0

一些与这些功能:子(FirstIndexOf( '#'),LastIndexOf( '#')); – Karl 2013-02-14 08:27:02

+1

如果字符串不包含部分'#item#',返回什么? – 2013-02-14 08:29:25

回答

8

你可以看看Regex.Match。如果你知道正则表达式一点点(你的情况这将是一个相当简单的模式:"#[^#]+#"),你可以用它来提取开始,以'#'与任意数量的比之间'#'等其他字符结尾的所有项目。

例子:

Match match = Regex.Match("Item 3: #item3#", "#[^#]+#"); 
if (match.Success) { 
    Console.WriteLine(match.Captures[0].Value); // Will output "#item3#" 
} 
0

如何:

List<string> substring_list = new List<string>(); 
foreach (string item in list) 
{ 
    int first = item.IndexOf("#"); 
    int second = item.IndexOf("#", first); 
    substring_list.Add(item.Substring(first, second - first); 
} 
0

你可以做到这一点通过简单的使用:

List<string> list2 = new List<string>(); 
    list.ForEach(x => list2.Add(x.Substring(x.IndexOf("#"), x.Length - x.IndexOf("#")))); 
0

尝试。

var itemList = new List<string>(); 
foreach(var text in list){ 
string item = text.Split(':')[1]; 
itemList.Add(item); 


} 
1

LINQ会做的工作很好:

var newList = list.Select(s => '#' + s.Split('#')[1] + '#').ToList(); 

或者如果你喜欢的查询表达式:

var newList = (from s in list 
       select '#' + s.Split('#')[1] + '#').ToList(); 

或者,您可以使用正则表达式与Botz3000建议,并结合那些LINQ:

var newList = new List(
    from match in list.Select(s => Regex.Match(s, "#[^#]+#")) 
    where match.Success 
    select match.Captures[0].Value 
); 
1

该代码将解决您的问题。 但如果字符串的不包含#item#那么原始字符串将被使用。

var inputList = new List<string> 
    { 
     "Item 1: #item1#", 
     "Item 2: #item2#", 
     "Item 3: #item3#", 
     "Item 4: item4" 
    }; 

var outputList = inputList 
    .Select(item => 
     { 
      int startPos = item.IndexOf('#'); 
      if (startPos < 0) 
       return item; 

      int endPos = item.IndexOf('#', startPos + 1); 
      if (endPos < 0) 
       return item; 
      return item.Substring(startPos, endPos - startPos + 1); 
     }) 
    .ToList(); 
2

这是另一种在LINQ中使用正则表达式的方法。 (不确定你的具体要求参考正则表达式,所以现在你可能有两个问题。)

var list = new List<string>() 
{ 
    "Item 1: #item1#", 
    "Item 2: #item2#", 
    "Item 3: #item3#", 
    "Item 4: #item4#", 
    "Item 5: #item5#", 
}; 

var pattern = @"#[A-za-z0-9]*#"; 

list.Select (x => Regex.Match (x, pattern)) 
    .Where (x => x.Success) 
    .Select (x => x.Value) 
    .ToList() 
    .ForEach (Console.WriteLine); 

输出:

# # ITEM1

# # ITEM2

# #项目3

# ITEM4 #

# # ITEM5