繁体   English   中英

如何正则表达式匹配 python 中的模式列表

[英]How to regex match list of patterns in python

我有模式列表,如果给定字符串中存在该模式,我需要返回该模式,否则返回无。 我尝试使用 re 模块使用以下代码,但我在“匹配”中只得到 null(当我尝试打印匹配时)。 对 corepython 和 regex 完全陌生,请帮助

import re
patterns_lst=['10_TEST_Comments','10_TEST_Posts','10_TEST_Likes']

def get_matching pattern(filename):
   for pattern in patterns_lst:
     matches = re.(pattern,filename)
   if matches:
      return matches
   else:
      return None

print(get_matching pattern("6179504_10_TEST_Comments_22-Nov-2021_22-Nov-2021.xlsx"))

我对您的 function 做了一些更改:

def get_matching_pattern(filename):            ## Function name changed
    for pattern in patterns_lst:
        match = re.search(pattern, filename)   ## Use re.search method

        if match:                              ## Correct the indentation of if condition
            return match                       ## You also don't need an else statement

Output:

>>> print(get_matching_pattern("6179504_10_TEST_Comments_22-Nov-2021_22-Nov-2021.xlsx"))
<re.Match object; span=(8, 24), match='10_TEST_Comments'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM