Generating the Shortest Regex Dynamically from a source List of Strings

前端 未结 3 657
一整个雨季
一整个雨季 2021-01-04 10:13

I have a bunch of SKUs (stock keeping units) that represent a series of strings that I\'d like to create a single Regex to match for.

So, for example, if I have SKUs

3条回答
  •  失恋的感觉
    2021-01-04 11:15

    This works if each SKU id have the same length.

    // ...
    string regexStr = Calculate(skus);
    // ...
    
    public static string Calculate(IEnumerable rest) {
        if (rest.First().Length > 0) {
            string[] groups = rest.GroupBy(r => r[0])
                .Select(g => g.Key + Calculate(g.Select(e => e.Substring(1))))
                .ToArray();
            return groups.Length > 1 ? "(" + string.Join("|", groups) + ")" : groups[0];
        } else {
            return string.Empty;
        }
    }
    

提交回复
热议问题