python - 将脚本从 Powershell 转换为 Python-Regex 未按预期工作

标签 python regex

我正在尝试将 Powershell 脚本转换为 python 脚本。我打算使用 Shell 脚本来简化 grep 和 curl 的使用,但为了简化 if 语句,我决定使用 python。 这是我要转换的 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 ($Image in $ReturnedRegExImageData) 这一行: 我试过在 ReturnedRegExData 中使用 for Image 和从 0 到 len(ReturnedRegExData) 的 for 循环,但它们没有返回有效数据。我知道 Python 应该是简单的编码,但我很难处理它。

我读过关于 .match、/search 和 .findall 的类似帖子,它们都涉及搜索部分,但没有涉及如何以有用的格式获取结果。我已经阅读了手册,但我也很难理解它。

如何遍历 findall 找到的结果,是否返回 0、1 或更多结果。 0 应该被 if 语句覆盖。

感谢您提供的任何帮助。

J

最佳答案

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" /><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)

关于python - 将脚本从 Powershell 转换为 Python-Regex 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012378/

相关文章:

python pandas : assign control vs. 根据 % 随机处理分组

正则表达式选择多个组

c# - 获取网页中所有 url 的列表

python - Python 中的单行 for 循环是如何工作的? [列表理解]

regex - Java替换所有方法附加替换字符串而不是替换

regex - 使用 grep/sed/awk 列出 2 个关键字之间的行

java - 将字符串中的所有单词集替换为其他单词集

python - True Loop 无法正常工作时的套接字

python - 正则表达式匹配 Python 中的非数值或字符串结尾

python - 如何使用python在selenium中的chrome驱动程序中加载扩展