新手问题 怎么用正则表达式分解 URI?

gsky · 2015年05月12日 · 最后由 winnie 回复于 2015年05月12日 · 4632 次阅读

我在一本参考书上看到这样一段代码可以将 URI 分解成协议,域名地址,页面和路径四个部分:

(\w+):\/\/([^/:]+)(:\d*)?([^#]*)

可是自己试的时候,无法匹配到,试验的 URI 是"http://www.wrox.com:80/misc-pages/support.shtml". 这是什么原因呢?

(\w+):\/\/ 这一部分的正确匹配了,后面就找不到匹配不到的原因了..

(\w+):\/\/([^\/:]+)(:\d*)?([^#]*) 正斜杠要转义。

#1 楼 @yesmeck 果然是这样,谢谢~~

其实也可以用addressable

为嘛不用URI("http://www.wrox.com:80/misc-pages/support.shtml")

https://github.com/ryan-endacott/verbal_expressions

# Create an example of how to test for correctly formed URLs
tester = VerEx.new do
  start_of_line
  find 'http'
  maybe 's'
  find '://'
  maybe 'www.'
  anything_but ' '
  end_of_line
end

# Create an example URL
test_url = "https://www.google.com"

# Use it just like a regular Ruby regex:
puts 'Hooray!  It works!' if tester.match(test_url)
puts 'This works too!' if tester =~ test_url

# Print the generated regex:
puts tester.source # => /^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$/

是不是很性感啊?还有各个语言的版本:

  • Ruby
  • C#
  • Python
  • Java
  • Groovy
  • PHP
  • Haskell
  • C++
  • Objective-C
需要 登录 后方可回复, 如果你还没有账号请 注册新账号