繁体   English   中英

Python:使用两个变量字符串作为 Regex.findall 标准

[英]Python: Using two variable strings as Regex.findall criteria

怎么了伙计们,我尝试接收两个字符串,并尝试找到两个字符串填充的每个文本。 例如:

Pattern_text = '\|\|####\|\|' #To be received from user
first_half= Pattern_text [0:len(Pattern_text )//2]  # to get left side of pattern \\##
second_half= Pattern_text [len(Pattern_text )//2:]  # to get right side of pattern ##\\
#Sample text
SEARCH_ME = r"BLABLABLA BLA ||##MATCH_ID_1548##|| BLA ||##MATCH_ID_3412##|| BLABLABLA"
#Trying to find all matches padded by the two halves
results = re.findall((first_half+ r'(.*?)'+second_half), SEARCH_ME)
print(results)

在这种情况下,结果总是空的。 预期结果应该是一个列表,其元素是'MATCH_ID_1548'和'MATCH_ID_3412'

您认为我应该如何处理这两个字符串变量,因为我确信连接字符串 (first_half + '(.*?)' + second_half) 的正则表达式在硬编码时有效。 但不是那种格式。

提前致谢。

这是我的工作的一个简单示例。 如果您在问题中提供完整且可重复的示例,我们将能够为您提供更多帮助。

import re

prefix = "prefix #"
suffix = "# suffix"

regex = fr"{prefix}(.*?){suffix}"  # Renders as "prefix #(.*?)# suffix"
test_string = "prefix #TEST STRING# suffix"

print(re.findall(regex, test_string))  # ['TEST STRING']

这是另一种方式。 它也适用于您的 4 位匹配 ID 扩展到 5 位或更多的情况。

import re

SEARCH_ME = r"BLABLABLA BLA ||##MATCH_ID_1548##|| BLA ||##MATCH_ID_3412343434##|| BLABLABLA"

print(re.findall(re.compile('(?:MATCH_ID_[0-9]{4,})'), SEARCH_ME))

结果:

['MATCH_ID_1548', 'MATCH_ID_3412343434']

暂无
暂无

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

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