如何在 if... else... 语句中使用 python 正则表达式? [英] How to use python regular expression inside if... else... statement?
问题描述
我的 Python 脚本:
My Python script:
import wget
if windowsbit == x86:
url = 'http://test.com/test_windows_2_56_30-STEST.exe'
filename = wget.download(url)
else:
url = 'http://test.com/test_windows-x64_2_56_30-STEST.exe'
filename = wget.download(url)
在上面的 python 脚本中,我使用 wget
模块下载基于 Windows 32 位或 64 位的文件格式 URL.它按预期工作.
In above python script, I am using wget
module to download a file form URL, based on windows 32 bit or 64 bit. Its working as expected.
我想用正则表达式做以下事情:
I want to use regular expression to do the following:
如果windowsbit == x86
,它应该下载以test_windows
开头并以STEST.exe
结尾的文件.否则它应该下载以 test_windows-x64
开头并以 STEST.exe
结尾的文件.
if windowsbit == x86
, its should download the file that starting with test_windows
and ends with STEST.exe
file.
else its should download file that starting with test_windows-x64
and ends with STEST.exe
file.
我是 python 新手,我不知道如何做到这一点.有人可以指导我吗?
I am new to python, I not getting any idea on how to do this. Could any one guide me on this?
推荐答案
这看起来不可能.与您要执行的操作相匹配的正则表达式类似于:
This doesn't look possible. The regular expression that would match what you're trying to do is something like:
import re
urlre = re.compile("""
http://test.com/test_windows # base URL
(?P<bit>-x64)? # captures -x64 if present
_(?P<version_major>\d+) # captures major version
_(?P<version_minor>\d+) # captures minor version
_(?P<version_revision>\d+) # captures revision version
-STEST.exe # ending filename""", re.X)
然而,你不能把它扔到 wget
中.您不能在请求中使用通配符——网络服务器必须知道如何处理它们,而它不知道.更好的方法可能是:
However you can't just throw that in wget
. You can't use wildcards in requests -- the webserver would have to know how to process them and it doesn't. A better method might be:
base_url = "http://test.com/test_windows"
if windowsbit == x64:
base_url += "-x64"
version = "2_56_30"
filename = "STEST.exe"
final_url = "{base}_{version}-{filename}".format(
base=base_url, version=version, filename=filename)
这篇关于如何在 if... else... 语句中使用 python 正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!