我必须编写一个脚本,它将在命令行输入主机名。但是,用户以pdsh格式输入主机名。有没有更简单的方法从pdsh格式中解析和提取主机名。
example for pdsh format:
myhost[01-03]
it means we are referring hostnames - "myhost01", "myhost02" and "myhost03"我需要提取上面提到的主机名,稍后我将在脚本中使用这些名称。我相信这可以用regex来完成,这可能有点笨拙。但是在python中有没有更简单的方法。
发布于 2016-03-16 11:56:38
就这样做,
>>> 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']
>>> https://stackoverflow.com/questions/36034836
复制相似问题