首页 > 解决方案 > 提取字符串c#之间的所有重复子字符串

问题描述

有一个string s = "City, State, Country, City,State,Country"

并返回List<string>[0] = ["City, State, Country"] and List<string>[1] = ["City,State,Country"]

想过使用列表,但只返回第一个匹配的,它会在搜索第二个匹配的字符串时出错。有人可以帮我吗?感谢!

    private static List<string> ExtractFromBody(string body, string start, string end)
    {
        List<string> matched = new List<string>();

        int indexStart = 0;
        int indexEnd = 0;

        bool exit = false;
        while (!exit)
        {
            indexStart = body.IndexOf(start);

            if (indexStart != -1)
            {
                indexEnd = indexStart + body.Substring(indexStart).IndexOf(end);

                matched.Add(body.Substring(indexStart + start.Length, indexEnd - indexStart - start.Length));

                body = body.Substring(indexEnd + end.Length);
            }
            else
            {
                exit = true;
            }
        }

        return matched;
    }

标签: c#.net

解决方案


这是使用正则表达式有意义的一种情况。我假设提取应该区分大小写,如果不是,则RegexOptions.IgnoreCase可以将选项Regex.Matches作为第三个参数传递给方法。

public List<string> ExtractFromBody(string body, string start, string end) =>
    Regex.Matches(body, $@"{start}.+?{end}")
         .Cast<Match>()
         .Select(m => m.Value)
         .ToList();

这会找到所有Regex以开头start和结尾的匹配项,end然后转换为字符串列表。

在 LINQPad 中像这样使用它:

var s = "City, State, Country, abcd City, State, Country";
var start = "City";
var end = "Country";

ExtractFromBody(s,start,end).Dump();

输出是:

List<String> (2 items)
City, State, Country
City, State, Country

推荐阅读