[英]match a substring in a list of substrings
There is a better way to do with with regex, 使用正则表达式有更好的方法,
>>> HOSTS=['backup-ros', 'backupa-files', 'print-server1','print-server2']
>>> for host in HOSTS:
... if 'backup' in host:
...
backup-ros
backupa-files
which is partially correct. 这是部分正确的。
I tried this: 我尝试了这个:
a=re.findall(r'backup-(\w+)', ' '.join(HOSTS))
>>> a
['ros']
which gave me 'ros'. 这给了我“罗斯”。
And finally: 最后:
a=re.match(r'backup-(\w+)', ' '.join(HOSTS))
>>> a.group()
'backup-ros'
Which I think is correct. 我认为是正确的。 However, I still wanted to ask if this is the right way the better way to do it.
但是,我仍然想问这是否是正确的方法,是更好的方法。
EDIT: I realized after a few comments, that it's not clear what I'm looking for. 编辑:几句话后,我意识到,不清楚我在寻找什么。 I needed to find the names of directories called "backup-somename" inside a directory.
我需要在目录中找到名为“ backup-somename”的目录的名称。 But I didn't want to include the directories who's name is for example "backupa-somename" or "backupb-somename".
但是我不想包括名称为“ backupa-somename”或“ backupb-somename”的目录。 That is why my first for loop was not good enough for me.
这就是为什么我的第一个for循环对我来说不够好。
Thanks, in advance. 提前致谢。 Oz
奥兹
Without regex, could you consider .startswith()
? 没有正则表达式,您可以考虑使用
.startswith()
吗?
>>> HOSTS = ['backup-ros', 'backupa-files', 'print-server1','print-server2']
>>> backups = [x for x in HOSTS if x.startswith('backup-')]
>>> backups
['backup-ros']
No need to join the list into a string. 无需将列表加入字符串中。
Instead of this 代替这个
a=re.findall(r'backup-(\w+)', ' '.join(HOSTS))
use 采用
a=re.findall(r'(backup-[\w]+)', ' '.join(HOSTS)).
The issue was your regex was matching whole pattern but was grouping \\w+ at the end. 问题是您的正则表达式匹配整个模式,但最后将\\ w +分组。 This is a simpler way
这是一个更简单的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.