[英]Match everything until optional string (Python regex)
我已經對這個問題投入了很多精力,似乎我錯過了一些瑣碎的事情,因此提前致歉。 我有一個網址,其中可能包含或可能不包含一些POST值。 我要匹配整個網址,直到這個可選部分(不包括在內)為止。 因此,例如:
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 =....。
我嘗試了各種非貪婪的雜技,但令我失望的部分是第二部分是可選的,因此沒有什么可以“錨定”非貪婪的比賽的。 任何想法如何優雅地做到這一點? 只有第一部分很重要。 也歡迎非正則表達式解決方案
謝謝!
我建議您在進行網址解析時避免使用正則表達式,而應使用此模塊 ,這是解決您的問題的有效示例:
import urlparse
myurl = 'http://myAddress.com/index.aspx?cat=ThisPartChanges&pageNum=41'
parsed = urlparse.urlparse(myurl)
print 'scheme :', parsed.scheme
print 'netloc :', parsed.netloc
print 'path :', parsed.path
print 'params :', parsed.params
print 'query :', parsed.query
print 'fragment:', parsed.fragment
print 'username:', parsed.username
print 'password:', parsed.password
print 'hostname:', parsed.hostname, '(netloc in lower case)'
print 'port :', parsed.port
print urlparse.parse_qs(parsed.query)
就您而言,這可以做到:
^[^&]+
更強大:
^[^?]+\?cat=[^&]+
例:
In [40]: s = 'http://myAddress.com/index.aspx?cat=ThisPartChanges&pageNum=41'
In [41]: re.search(r'^[^&]+', s).group()
Out[41]: 'http://myAddress.com/index.aspx?cat=ThisPartChanges'
In [42]: re.search(r'^[^?]+\?cat=[^&]+', s).group()
Out[42]: 'http://myAddress.com/index.aspx?cat=ThisPartChanges'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.