要捕获命令行参数组的正则表达式,你可以使用以下的解决方法:
import re
# 定义命令行参数模式
pattern = re.compile(r'--(?P\w+)\s+(?P\w+)')
# 假设命令行参数是 "--name John --age 25 --gender male"
command_line = "--name John --age 25 --gender male"
# 使用findall函数查找所有命令行参数组
matches = pattern.findall(command_line)
# 遍历匹配结果
for match in matches:
arg = match[0]
value = match[1]
print(f"参数:{arg},值:{value}")
import re
# 定义命令行参数模式
pattern = re.compile(r'--(\w+)\s+(\w+)')
# 假设命令行参数是 "--name John --age 25 --gender male"
command_line = "--name John --age 25 --gender male"
# 使用findall函数查找所有命令行参数组
matches = pattern.findall(command_line)
# 遍历匹配结果
for match in matches:
arg = match[0]
value = match[1]
print(f"参数:{arg},值:{value}")
这两种方法都使用正则表达式的findall
函数来查找所有匹配的命令行参数组。第一种方法使用命名捕获组来命名参数和值,第二种方法使用非命名捕获组。根据你的需要,选择适合的方法来解析命令行参数。
上一篇:捕获命令的退出码并在之后返回它。
下一篇:捕获模块的所有异常