【发布时间】:2012-11-26 06:27:52
【问题描述】:
如何匹配如下 URL:
http://www.example.com/foo/:id/bar
http://www.example.com/foo/1/bar
http://www.example.com/foo/999/bar
stub_request(:post, "www.example.com")
【问题讨论】:
-
您是否在寻找匹配 URL 模式的正则表达式?
如何匹配如下 URL:
http://www.example.com/foo/:id/bar
http://www.example.com/foo/1/bar
http://www.example.com/foo/999/bar
stub_request(:post, "www.example.com")
【问题讨论】:
您可以在 Ruby 中使用 %r{} 而不是 // 作为正则表达式,以避免转义 URL 中的正斜杠。例如:
stub_request(:post, %r{\Ahttp://www.example.com/foo/\d+/bar\z})
【讨论】:
{} 来关闭正则表达式,例如%r() 或%r'' 这很有帮助,因为正则表达式数量修饰符使用花括号。因此,如果您尝试匹配 URL 或具有特定字符数的内容(例如 36 个字符的 API 密钥),请使用括号之类的内容来关闭正则表达式。
stub_request 的第二个参数必须是正则表达式,而不是字符串。
stub_request(:post, /http:\/\/www.example.com\/foo\/\d+\/bar/)
【讨论】:
http://www\..*?\.com/foo/\d+/bar 应该适合你。
【讨论】:
\. 正在转义. 点字符,而.*? 表示任何字符(点字符表示任何字符)零次或多次(* 是零次或多次而+ 是 1 次或更多次)并使其不贪婪(问号 ?),所以它一碰到 .com 就停止查找。