我已经为这个问题绞尽脑汁,似乎我遗漏了一些非常微不足道的东西,所以提前道歉。我有一个 url,它可能包含也可能不包含一些 POST 值。我想匹配整个 url 直到这个可选部分(不包括在内)。例如:
import re
myurl = r'http://myAddress.com/index.aspx?cat=ThisPartChanges&pageNum=41'
matchObj = re.match(r'(.*?)(&pageinfo=\d+){0,1}', myurl)
print matchObj.groups()
>> ('', None)
# Putting the non-greedy ? outside
matchObj = re.match(r'(.*)?(&pageinfo=\d+){0,1}', myurl)
print matchObj.groups()
>> ('http://myAddress.com/index.aspx?cat=ThisPartChanges&pageNum=41', None)
# The url might also be without the last part, that is
myurl = r'http://myAddress.com/index.aspx?cat=ThisPartChanges'
# I'd like the regex to capture the first part. "ThisPartChanges" might
# be different every time
我想要的是获取 pageNum=\d+ 之前的所有内容,不包括在内。 也就是
http://myAddress.com/index.aspx?cat=ThisPartChanges
我只对 &pageNum 之前的部分感兴趣,并不关心它是否存在,只是想以某种方式将其过滤掉,以便我可以获得真实地址,直到 cat=....
我尝试过各种非贪婪技巧,但让我失望的部分是第二部分是可选的,因此没有什么可以“锚定”非贪婪匹配。 任何想法如何优雅地做到这一点?只有第一部分很重要。也欢迎使用非正则表达式解决方案
谢谢!
请您参考如下方法:
