从字符串中获取特定模式的子字符串(C#)

7

我有一个字符串列表,类似于这样:

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

如何获取并将子字符串 #item1#,#item2#等添加到新列表中?

如果字符串包含“#”,我只能通过以下方式获取完整字符串:

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

使用以下函数:substring(FirstIndexOf('#'), LastIndexOf('#')); - abc
1
如果字符串不包含部分 #item#,应该返回什么? - Sergey Vyacheslavovich Brunov
7个回答

14
你可以看看 Regex.Match。如果你了解一点正则表达式(在你的情况下,这将是一个相当简单的模式:"#[^#]+#"),你可以使用它提取所有以'#'开始和结束的项目,并在中间包含任意数量的其他字符,除了'#'
示例:
Match match = Regex.Match("Item 3: #item3#", "#[^#]+#");
if (match.Success) {
    Console.WriteLine(match.Captures[0].Value); // Will output "#item3#"
}

3

以下是使用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);

输出:

#项目1#

#项目2#

#项目3#

#项目4#

#项目5#


2
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();

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


}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接