3

我正在寻找一个单一的正则表达式,它将匹配长度为 1 个或多个匹配的字符500。这将在 Rails 路由文件中使用,特别是用于处理异常。

路线.rb

match '/500', to: 'errors#server_error'
match '/:anything', :to => "errors#not_found", :constraints => { :anything => /THE REGEX GOES HERE/ }

我对如何定义匹配某些东西但同时不匹配其他东西的正则表达式有点迷茫。

4

4 回答 4

2

您可以使用此正则表达式来检查字符串是否不包含子字符串 500:

\A(?>[^5]++|5++(?!00))+\z

如果你想允许 5000 或 5500...,你可以这样做:

\A(?>[^5]++|5{2,}+|5(?!00(?!0)))+\z

第一个字符串解释:

\A           # begining of the string
(?>          # opening of an atomic group
   [^5]++    # all characters but 5 one or more times (possessive)
  |          # OR
   5++(?!00) # one or more 5 not followed by 00
)+           # closing of the atomic group, one or more times
\z           # end of the string

占有量词原子组在这里是为了避免正则表达式引擎回溯以获得更好的性能(正则表达式很快失败)。

于 2013-06-13T14:32:40.980 回答
1

Rails routes are matched in the order that they appear in routes.rb. By putting /500 first (or higher up) in the list, it guarantees that the routes further down do not match /500. You shouldn't have to worry about this.

So, instead, split this into more routes.

match '/500', to: 'errors#server_error'
match '.*500.*', to: 'somewhere else'
match '/:anything', :to => "errors#not_found"

and don't worry about the constraint.

于 2013-06-13T15:02:42.530 回答
1

你真的需要那个正则表达式吗?您的路线定义

match '/500', to: 'errors#server_error'

将捕获所有这些/500请求,这意味着您的下一个路由规则

match '/:anything', :to => "errors#not_found"

不会自动获取它们。

于 2013-06-14T08:56:30.497 回答
0

正如评论中所述,这个正则表达式应该可以完成这项工作\A(?!500\z).+\z

解释

  • \A: 匹配行首
  • (?!500\z):负前瞻,这意味着检查是否没有 500 + 行尾\z
  • .+: 匹配任意字符一次或多次
  • \z: 匹配行尾
于 2013-06-13T21:17:00.973 回答