3

我最近一直在尝试使用 Sinatra,并且在基于正则表达式的路由方面遇到了一些“问题”......例如,

get "/something/" do
  status 400
end

匹配/something但不匹配/something/也不匹配/somethingelse。然而,

get %r{/something/([0-9]{3})} do |number|
  status number
end

匹配/something/201但也/something/201/something/201-and-somethingelse。也许我应该重写正则表达式来阅读%r{/something/([0-9]+)$},但包含美元符号对我来说没有意义,因为这种捕获应该是严格的,对吧?还是我错过了什么?

4

1 回答 1

2

Sinata 遵循 Ruby 的常规正则表达式规则。从 IRB 会话:

pattern = %r{/something/([0-9]{3})}
=> something[0-9]{3}
pattern.match "/something/201"
=> #<MatchData "/something/201" 1:"201">
pattern.match "/something/201/"
=> #<MatchData "/something/201" 1:"201">
pattern.match "something/201-and-somethingelse"
=> nil
pattern.match "/something/201-and-somethingelse"
=> #<MatchData "/something/201" 1:"201">

(这考虑到我上面指出的错字)。

您的另一个示例get "/something/" do是字符串,而不是正则表达式,但可以包含某些模式以方便使用,例如?. 所以:

get "/something/" do # will match "/something/" but not "/something"
get "/something" do # will match "/something" but not "/something/"
get "/something/?" do # will match "/something" and "/something/"
于 2013-02-01T12:25:24.217 回答