从pdsh格式解析

时间:2016-03-16 11:48:31

标签: python regex format

我必须编写一个脚本,它将在命令行中获取主机名的输入。但是,用户以pdsh格式输入主机名。 有没有更简单的方法来解析和提取所提供的pdsh格式的主机名。

example for pdsh format:
myhost[01-03]
it means we are referring hostnames - "myhost01", "myhost02" and "myhost03"

我需要提取上面提到的主机名,稍后我将在脚本中使用。 我相信这可以使用正则表达式来完成,这可能有点笨拙。但有没有更简单的方法在python中做到这一点。

1 个答案:

答案 0 :(得分:2)

就这样做,

>>> import re
>>> s = 'myhost[01-03]'
>>> k, num1, num2 = re.search(r'(.+?)\[(\d+)-(\d+)', s).groups() # Gets the first word, first number, second number and stores it to their respective variables
>>> [k + '{0:02d}'.format(i) for i in range(int(num1), int(num2)+1)] # format function here is used to pad zeros if there is only one digit exists.
['myhost01', 'myhost02', 'myhost03']

您可以将其定义为单独的功能。

>>> def get_host(s):
    k, num1, num2 = re.search(r'(.+?)\[(\d+)-(\d+)', s).groups()
    return [k + '{0:02d}'.format(i) for i in range(int(num1), int(num2)+1)]

>>> print get_host('myhost[01-13]')
['myhost01', 'myhost02', 'myhost03', 'myhost04', 'myhost05', 'myhost06', 'myhost07', 'myhost08', 'myhost09', 'myhost10', 'myhost11', 'myhost12', 'myhost13']
>>>