简体   繁体   English

匹配子字符串列表中的子字符串

[英]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.

相关问题 匹配子字符串和字符串列表,如果匹配则返回子字符串 - Match list of substrings and strings and return substring if it matches 查找与列表匹配的子字符串 - Find substrings that match a list Python - 从子字符串列表中搜索列表中的子字符串 - Python - Search for substring in list from a list of substrings 如何拆分字符串并将其子字符串与子字符串列表相匹配? - Python - How to split a string and match its substrings to a list of substrings? - Python 使用子字符串列表进行子字符串搜索后返回列表条目 - Returning a list entry after a substring search using list of substrings 匹配包含给定子字符串列表的文件名 - Match file names containing a given list of substrings Python:排序子字符串列表而不创建每个子字符串的单独副本 - Python: Sorting a list of substrings without creating a separate copy of each substring 如果子字符串在列表中,则保留子字符串 - Keep substrings if substrings are in a list 从字符串列表中获取子字符串列表,其中子字符串与某个正则表达式匹配 - Get a list of substrings from a list of strings where the substrings match a certain regular expression pandas DataFrame多个子字符串匹配,也将一行的特定匹配子字符串放入新列 - pandas DataFrame multiple substrings match, also put the particular matched substring for a row into a new column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM