3

Given a list of strings like so:

a/b/*/lol/cats
*/*
foo/bar/**
foo/bar/*/C/**

How would you sort them by specificity?

My naive approach (which works for the majority of my test cases) is as follows:

var sorted = wildCards
    .OrderBy(c => c.HasCatchAll)
    .ThenBy(c => c.NumWildCards)
    .ThenByDescending(c => c.Pattern.Length);

In the above code the HasCatchAll property indicates that the string has a ** at the end (the only valid place for a **).

My reasoning for above is that anything with a ** is less specific than a wild card without, and the more wild cards you have the less specific you are being. That said, the above will fail for:

*/hi/*/*
*/*/hi/*

Any help would be greatly appreciated.

4

1 回答 1

1

假设您有一个比较功能,那么为您的列表构建排序算法很容易。

问题是如何定义这样的函数。也许你可以这样定义:

  • 两个字符串作为输入 (a, b)
  • 如果两个字符串相互匹配 => a == b
  • 如果两个字符串不匹配=>更详细的比较,比如你的 HasCatch 东西......
  • 如果第一个字符串匹配第二个 => a < b
  • 如果第二个字符串匹配第一个 => a > b

匹配例如:*foo。这里*匹配foo,但不是相反。

使用它,您可以覆盖此案

*/hi/*/*
*/*/hi/*

这会说它们都相互匹配,这意味着它们具有相同的顺序。

长话短说:我认为您的解决方案不会失败。将这两个字符串定义为“相等”是有意义的,不是吗?

第二个想法:如果您在这样的字符串中优先考虑您的条目:1/2/3/4....您也可以规避您的问题..在这种情况下*/hi/*/*更具体

于 2012-06-11T22:53:50.233 回答