我有模式串列,如果給定字串中存在該模式,我需要回傳該模式,否則回傳 None。我嘗試使用 re module 使用下面的代碼,但我在“匹配”中只得到空值(當我嘗試列印匹配時)。對 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"))
uj5u.com熱心網友回復:
我對您的功能進行了一些更改:
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
輸出:
>>> 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'>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/392889.html
