我正在寻找一个正则表达式,该表达式将匹配长度为1个或更多字符的内容,这些字符的长度为而不是匹配500。这将在Rails路由文件中使用,特别是用于处理异常。
routes.rb
match '/500', to: 'errors#server_error'
match '/:anything', :to => "errors#not_found", :constraints => { :anything => /THE REGEX GOES HERE/ }我有点迷茫,不知道如何定义正则表达式匹配的东西,同时不匹配其他的东西。
发布于 2013-06-13 14:32:40
可以使用此regex检查字符串是否不包含子字符串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占有量词和原子群在这里是为了避免regex引擎回溯以获得更好的性能( regex很快就会失败)。
发布于 2013-06-13 15:02:42
Rails路由按照它们在routes.rb中出现的顺序进行匹配。通过将/500放在列表的第一位(或更高的位置),它保证了进一步向下的路由与/500不匹配。你不应该担心这个。
所以,相反,把它分成更多的路线。
match '/500', to: 'errors#server_error'
match '.*500.*', to: 'somewhere else'
match '/:anything', :to => "errors#not_found"别担心约束。
发布于 2013-06-14 08:56:30
你真的需要那个Regex吗?你的路线定义
match '/500', to: 'errors#server_error'
将捕获所有这些/500请求,这意味着您的下一个路由规则
match '/:anything', :to => "errors#not_found"
不会自动得到的。
https://stackoverflow.com/questions/17088913
复制相似问题