match trailing slash with Python regex

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

I try to match a trailing / like this:

type(re.match('/$', u'https://x.x.x/')) <type 'NoneType'> 

However, this one does match:

type(re.match('.*/$', u'https://x.x.x/')) <type '_sre.SRE_Match'> 

Using Perl the first pattern does match:

perl -e 'print "true" if "https://example.org/" =~ /\/$/' 

How can this behavior be explained?

回答1:

re.match search your pattern from beginning of you string. Since your string doesn't start with a '/', re.match('/$', u'https://x.x.x/') returns nothing.

You need to use re.search('/$', u'https://x.x.x/') to find your last slash.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!