python2.7中正则匹配URL

qq_37972009 2017-12-06 04:26:48
请问python2.7中使用正则如何去匹配"/hello/world/?sys=name"
这个的地址,并取出前2个字段 "hello" "world" .
之前试了使用re.search re.findall() 都没成功。
...全文
271 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
extend 2017-12-07
  • 打赏
  • 举报
回复
引用 3 楼 xpresslink 的回复:
[quote=引用 2 楼 extend 的回复:] 你的这个问题,最好使用split 正则的话: >>> string '/hello/world/?sys=name' >>> print(re.findall(r"/*(\w+)/+",string)) ['hello', 'world'] 但有个问题,hello和world中间那个"/",是没法重复匹配的,也就是说,匹配了”/hello/“,就不能匹配”/world/“,只能匹配”world/“。 所以正则里,第一个"/"用的是"*"模式,就是为了照顾后面的world。 至少我现在不知道其它方法,有大牛能搞定这个问题吗?
>>> re.findall('(?<=/)(\w+)(?=/)', '/hello/world/?sys=name') ['hello', 'world'][/quote]
混沌鳄鱼 2017-12-06
  • 打赏
  • 举报
回复
引用 2 楼 extend 的回复:
你的这个问题,最好使用split 正则的话: >>> string '/hello/world/?sys=name' >>> print(re.findall(r"/*(\w+)/+",string)) ['hello', 'world'] 但有个问题,hello和world中间那个"/",是没法重复匹配的,也就是说,匹配了”/hello/“,就不能匹配”/world/“,只能匹配”world/“。 所以正则里,第一个"/"用的是"*"模式,就是为了照顾后面的world。 至少我现在不知道其它方法,有大牛能搞定这个问题吗?
>>> re.findall('(?<=/)(\w+)(?=/)', '/hello/world/?sys=name') ['hello', 'world']
oyljerry 2017-12-06
  • 打赏
  • 举报
回复
简单的你需要找到对应的分隔符,直接字符串查找都可以找出来
extend 2017-12-06
  • 打赏
  • 举报
回复
你的这个问题,最好使用split 正则的话: >>> string '/hello/world/?sys=name' >>> print(re.findall(r"/*(\w+)/+",string)) ['hello', 'world'] 但有个问题,hello和world中间那个"/",是没法重复匹配的,也就是说,匹配了”/hello/“,就不能匹配”/world/“,只能匹配”world/“。 所以正则里,第一个"/"用的是"*"模式,就是为了照顾后面的world。 至少我现在不知道其它方法,有大牛能搞定这个问题吗?

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧