正则表达式作为关联数组键?
Regex as associative array key?
我正在用 D 编写我的代码中非常依赖性能的部分。为此,我想要一个关联数组将我的数据映射到 Regex
,以便我以后可以使用它。
当我尝试执行此操作时,出现错误 index is not a type or expression
。我怎样才能使用这个正则表达式作为我的数组键?
编辑:对于代码,这是我要在 class 中定义的内容:
View[Regex] m_routes;
我想要这样,这样我就可以添加如下路线:
void add(string route, View view)
{
auto regex = regex(route.key, [ 'g', 'i' ]);
if (regex in m_routes)
throw new Exception(format(`Route with path, "%s", is already assigned!`, route));
m_routes[regex] = view;
}
这样我就可以根据路由检查正则表达式,而不必重建每个路由,如以下方法所示:
View check(string resource)
{
foreach (route; m_routes.byKeyValue())
{
auto match = matchAll(resource, route.key);
// If this regex is a match
// return the view
if (!match.empty)
{
return route.value;
}
}
return null;
}
任何帮助将不胜感激,谢谢!
似乎 std.regex.Regex 是一个带有类型参数的别名:
(来自 std.regex.package,版本 2.071.0 中的第 289 行)
public alias Regex(Char) = std.regex.internal.ir.Regex!(Char);
换句话说,您需要为正则表达式指定字符类型。对于 string
,那就是 char
:
View[Regex!char] m_routes;
我正在用 D 编写我的代码中非常依赖性能的部分。为此,我想要一个关联数组将我的数据映射到 Regex
,以便我以后可以使用它。
当我尝试执行此操作时,出现错误 index is not a type or expression
。我怎样才能使用这个正则表达式作为我的数组键?
编辑:对于代码,这是我要在 class 中定义的内容:
View[Regex] m_routes;
我想要这样,这样我就可以添加如下路线:
void add(string route, View view)
{
auto regex = regex(route.key, [ 'g', 'i' ]);
if (regex in m_routes)
throw new Exception(format(`Route with path, "%s", is already assigned!`, route));
m_routes[regex] = view;
}
这样我就可以根据路由检查正则表达式,而不必重建每个路由,如以下方法所示:
View check(string resource)
{
foreach (route; m_routes.byKeyValue())
{
auto match = matchAll(resource, route.key);
// If this regex is a match
// return the view
if (!match.empty)
{
return route.value;
}
}
return null;
}
任何帮助将不胜感激,谢谢!
似乎 std.regex.Regex 是一个带有类型参数的别名:
(来自 std.regex.package,版本 2.071.0 中的第 289 行)
public alias Regex(Char) = std.regex.internal.ir.Regex!(Char);
换句话说,您需要为正则表达式指定字符类型。对于 string
,那就是 char
:
View[Regex!char] m_routes;