代码之家  ›  专栏  ›  技术社区  ›  duhaime

Python:如何加快regex

  •  0
  • duhaime  · 技术社区  · 3 年前

    假设我有一个清单

    list = ['this','is','just','a','test']
    

    如何让用户进行通配符搜索?

    搜索词:'th_s'

    将返回“this”

    0 回复  |  直到 12 年前
        1
  •  198
  •   phihag    12 年前

    使用 fnmatch :

    import fnmatch
    lst = ['this','is','just','a','test']
    filtered = fnmatch.filter(lst, 'th?s')
    

    如果你想允许 _ 作为通配符,只是 replace 所有下划线都带有 '?' (对于一个字符)或 * (用于多个字符)。

    如果您希望用户使用更强大的筛选选项,请考虑允许他们使用 regular expressions .

        2
  •  62
  •   Yuushi    12 年前

    正则表达式可能是解决此问题的最简单方法:

    import re
    regex = re.compile('th.s')
    l = ['this', 'is', 'just', 'a', 'test']
    matches = [string for string in l if re.match(regex, string)]
    
        3
  •  0
  •   Kos    12 年前

    你是说通配符有什么特定的语法吗?通常 * 代表“一个或多个”字符,以及 ? 代表一。

    最简单的方法可能是将通配符表达式转换为正则表达式,然后使用它来过滤结果。

        4
  •  0
  •   Farhaan S.    7 年前

    与Yuushi使用正则表达式的想法相同,但这使用了re库中的findall方法,而不是列表理解:

    import re
    regex = re.compile('th.s')
    l = ['this', 'is', 'just', 'a', 'test']
    matches = re.findall(regex, string)
    
        5
  •  0
  •   Michel Soares    5 年前

    为什么不直接使用join函数呢?在regex findall()或group()中,您将需要一个字符串,因此:

    import re
    regex = re.compile('th.s')
    l = ['this', 'is', 'just', 'a', 'test']
    matches = re.findall(regex, ' '.join(l)) #Syntax option 1
    matches = regex.findall(' '.join(l)) #Syntax option 2
    

    join()函数允许您转换字符串中的列表。join之前的单引号是您将放在列表中每个字符串中间的内容。当您执行此代码部分(''.join(l))时,您将收到以下消息:

    “这只是一个测试”

    因此,您可以使用findal()函数。

    我知道我迟到了7年,但我最近创建了一个帐户,因为我正在学习,其他人可能会有同样的问题。我希望这能帮助你和其他人。


    @FlixBrunet评论后更新:

    import re
    regex = re.compile(r'th.s')
    l = ['this', 'is', 'just', 'a', 'test','th','s', 'this is']
    
    matches2=[] #declare a list
    for i in range(len(l)): #loop with the iterations = list l lenght. This avoid the first item commented by @Felix
    if regex.findall(l[i]) != []: #if the position i is not an empty list do the next line. PS: remember regex.findall() command return a list.
        if l[i]== ''.join(regex.findall(l[i])): # If the string of i position of l list = command findall() i position so it'll allow the program do the next line - this avoid the second item commented by @Félix
            matches2.append(''.join(regex.findall(l[i]))) #adds in the list just the string in the matches2 list
    
    print(matches2)
    
        6
  •  -10
  •   Buddy    7 年前

    简单的方法就是尝试 os.system :

    import os
    text = 'this is text'
    os.system("echo %s | grep 't*'" % text)