[英]Converting Script from Powershell to Python-Regex Not Working as Expected
我正在嘗試將Powershell腳本轉換為python腳本。 我打算使用一個Shell腳本來簡化grep和curl的使用,但我決定使用python來簡化if語句。 這是我想要轉換的Powershell代碼:
Powershell代碼(效果很好):
$ReturnedRegExData = SearchStringAll -StringToSearch $Data -RegEx $ImgURLRegex
if ($ReturnedRegExData) #Check Existance of Matches
{
foreach ($Image in $ReturnedRegExImageData) #Run Through all Matches
#Can then get the result from the group of results and run through them 1 at a time via $Image
}
else
{
#exit
}
這是我對Python的嘗試,而不是太好用
ReturnedRegExData = re.findall($ImgURLRegex , $Data)
if ReturnedRegExImageData: #Check existance of Matches (Works)
print "found"
else:
sys.stderr.write("Error finding Regex \r\n")
return
$For Loop running through results
re.search使用了這個打印版本ReturnedRegExImageData.group(0),但是我想找到所有的匹配,並且非常難以復制foreach($ Retur in $ ReturnedRegExImageData)這一行:我已經嘗試過亂用圖像了ReturnedRegExData和for循環從0到len(ReturnedRegExData),但它們不返回有效數據。 我知道Python應該是簡單的編碼,但我很難處理它。
我已經閱讀了.match,/ search和.findall的類似帖子,它們都遍布搜索部分,但沒有什么可以解決如何以有用的格式獲得結果。 我查看了手冊,但我也很難解讀它。
如何返回找到的結果,無論是返回0,還是1或更多結果。 0應該由if語句覆蓋。
感謝您的任何幫助,您可以提供。
Ĵ
findall
函數返回一個字符串列表。 所以你可以這樣做:
found = re.findall(img_url_regex, data)
if not found: # the list is empty
sys.stderr.write("Error finding Regex \r\n")
else:
for imgurl in found:
print 'Found image:', imgurl
# whatever else you want to do with the URL.
注意,使用$來啟動變量名是無效的python;
In [3]: $foo = 12
File "<ipython-input-3-38be62380e9f>", line 1
$foo = 12
^
SyntaxError: invalid syntax
如果要替換部分已找到的URL,可以使用sub()
方法。 它使用MatchObject
。 下面是我自己的一個腳本的示例。 我用它來改變例如<img alt='pic' class="align-left" src="static/test.jpg" />
to <img alt='pic' class="align-left" src="static/images/test.jpg" />
with open(filename, 'r') as f:
data = f.read()
# fix image links
img = re.compile(r'src="[\./]*static/([^"]*)"')
data = img.sub(lambda m: (r'src="' + prefix + 'static/images/' +
m.group(1) + r'"'), data)
with open(filename, 'w+') as of:
of.write(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.