在字符串列表中搜索任意数量的未知子字符串来代替 * [英] Search for any number of unknown substrings in place of * in a list of string

查看:61
本文介绍了在字符串列表中搜索任意数量的未知子字符串来代替 *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对不起,如果标题不是很明确,我很难正确地表述它.这也是为什么我没有发现这个问题是否已经被问过,是否已经被问过.

First of all, sorry if the title isn't very explicit, it's hard for me to formulate it properly. That's also why I haven't found if the question has already been asked, if it has.

所以,我有一个字符串列表,我想执行程序"搜索,用任何可能的子字符串替换目标子字符串中的每个 *.
下面是一个例子:

So, I have a list of string, and I want to perform a "procedural" search replacing every * in my target-substring by any possible substring.
Here is an example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('mesh_*')
# should return: ['mesh_1_TMP', 'mesh_2_TMP']

在只有一个 * 的情况下,我只是用 * 分割每个字符串并使用 startswith() 和/或 >endswith(),所以没关系.但是如果搜索字符串中有多个*,我不知道如何做同样的事情.

In this case where there is just one * I just split each string with * and use startswith() and/or endswith(), so that's ok. But I don't know how to do the same thing if there are multiple * in the search string.

所以我的问题是,如何在字符串列表中搜索任意数量的未知子字符串来代替 *?
例如:

So my question is, how do I search for any number of unknown substrings in place of * in a list of string?
For example:

strList = ['obj_1_mesh',
           'obj_2_mesh',
           'obj_TMP',
           'mesh_1_TMP',
           'mesh_2_TMP',
           'meshTMP']

searchFor('*_1_*')
# should return: ['obj_1_mesh', 'mesh_1_TMP']

希望一切都足够清楚.谢谢.

Hope everything is clear enough. Thanks.

推荐答案

如果我是你,我会为此使用正则表达式包.您必须学习一点正则表达式才能进行正确的搜索查询,但这还不错.在这种情况下,.+"与*"非常相似.

I would use the regular expression package for this if I were you. You'll have to learn a little bit of regex to make correct search queries, but it's not too bad. '.+' is pretty similar to '*' in this case.

import re

def search_strings(str_list, search_query):
    regex = re.compile(search_query)
    result = []
    for string in str_list:
        match = regex.match(string)
        if match is not None:
            result+=[match.group()]
    return result

strList= ['obj_1_mesh',
          'obj_2_mesh',
          'obj_TMP',
          'mesh_1_TMP',
          'mesh_2_TMP',
          'meshTMP']

print search_strings(strList, '.+_1_.+')

这应该返回 ['obj_1_mesh', 'mesh_1_TMP'].我试图复制 '*_1_*' 案例.对于mesh_*",您可以将 search_query 设为mesh_.+".这是 python regex api 的链接:https://docs.python.org/2/library/re.html

This should return ['obj_1_mesh', 'mesh_1_TMP']. I tried to replicate the '*_1_*' case. For 'mesh_*' you could make the search_query 'mesh_.+'. Here is the link to the python regex api: https://docs.python.org/2/library/re.html

这篇关于在字符串列表中搜索任意数量的未知子字符串来代替 *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆