[英]Python: Using two variable strings as Regex.findall criteria
What's up guys, I try to receive two strings, and try to find every text padded by the two strings.怎么了伙计们,我尝试接收两个字符串,并尝试找到两个字符串填充的每个文本。 For example:
例如:
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)
results is always empty in this case.在这种情况下,结果总是空的。 expected results should be a list whose elements are 'MATCH_ID_1548'and'MATCH_ID_3412'
预期结果应该是一个列表,其元素是'MATCH_ID_1548'和'MATCH_ID_3412'
What do you reckon I should do with those two string variables, knowing that I'm sure the regex of the concatenated string (first_half + '(.*?)' + second_half) works when hardcoded.您认为我应该如何处理这两个字符串变量,因为我确信连接字符串 (first_half + '(.*?)' + second_half) 的正则表达式在硬编码时有效。 But not in that format.
但不是那种格式。
Thanks in advance.提前致谢。
Here's a quick example of what's working on my end.这是我的工作的一个简单示例。 We would be able to help you a lot more if you provide a complete and reproducible example in the question.
如果您在问题中提供完整且可重复的示例,我们将能够为您提供更多帮助。
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']
Here is the another way.这是另一种方式。 It will also work on cases where your 4 digit match id scales to 5 digit or more.
它也适用于您的 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))
Result:结果:
['MATCH_ID_1548', 'MATCH_ID_3412343434']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.