【问题标题】:Regular Expression to match ranges of numbers except some certain ranges of numbers and some particular numbers [closed]正则表达式匹配数字范围,除了一些特定的数字范围和一些特定的数字[关闭]
【发布时间】:2013-12-08 04:59:45
【问题描述】:

我正在为每个用户创建用户安全策略。每个用户安全策略中都会有一个正则表达式语句。

每个网页都有自己唯一的ID,数字格式从0到100000。当用户访问一个网页时,系统会根据用户正则表达式的安全策略检查该网页的ID。

例如,用户可以访问除 ID 编号为 2、54、109 到 2001 和 10521 的网页之外的所有网页(ID 范围为 1 - 100000)。如何编写高效的正则表达式来解决这个要求?

【问题讨论】:

  • 最好用实际的编程语言来检查。只需将用户 ID 获取为任意数字并检查它是否在通常的if 范围内。它会更干净更短。
  • 为了说明为什么正则表达式不是此任务的正确工具,您建议的示例的正则表达式将是 ^(?!(2|54|109|1[1-9]\d|[2-9]\d{2}|1\d{3}|200[01]|10521)$)(\d{1,5}|100000)$。这是在诸如原子分组之类的性能优化(效率标准)之前,这将使表达式进一步复杂化。而且由于它具有安全功能,规范化漏洞(例如,前导零)将是一个潜在的问题。

标签: regex numeric


【解决方案1】:

您会发现这既是要维护的程序化噩梦,又是完成任务所需的巨大性能开销。您可能会发现使用列表更有效(并且不那么麻烦)。您可以将这些列表存储在数据库中,甚至可以使用与 RESTful 通信的云服务提供商。

一个例子,用php写的(大部分是伪代码),假设权限已经从数据存储中取回:

//user1 is logged in and has access to the following array of allowed pages:
$loggedInUserPerms = array(1,6,99,821,983255);
if (in_array($pageID, $loggedInUserPerms))
{
    //the logged in user has access to this page
}
else
{
    //the logged in user doesn't, display access denied error
}

你甚至可以扩展这个原理并使用多维数组:

$loggedInUserPerms = array(
    1=>array("read"),
    6=>array("read","write"),
    9=>array("read","write"),
    821=>array("read","write","delete"),
    983255=>array("read")
);
if (in_array($pageID, $loggedInUserPerms))
{
    //the logged in user has access to this page

    //you can now handle the sub arrays as well 
    //to determine what level of access the user has.
}
else
{
    //the logged in user doesn't, display access denied error
}

【讨论】:

  • 谢谢大家的回答。我对 regexp 很陌生,并认为它是正确的工具。我将按照您的建议在列表数据结构中实施安全策略。
  • 祝你好运!有很多关于正则表达式的信息——虽然它很强大,但你会发现人们经常在不了解在性能很重要的地方使用它的目的或编程开销的情况下转向它。
猜你喜欢
  • 2011-11-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多