我可以在Python的正则表达式中使用变量而不是常量吗

2024-04-25 19:51:11 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以在正则表达式中使用变量,如以下所示


target = ["New York", "the most"]
regex = r"((?:\w+\W+){3})(?=New York((?:\W+\w+){3}))"

test_str = "The City of New York often called New York City or simply New York is the most populous city in the " \
           "United States. With an estimated 2016 population of 8537673 distributed over a land area of about 3026" \
           "square miles (784 km2) New York City is also the most densely populated major city in the United States."

matches = re.finditer(regex, test_str)

for match in matches:
    print(re.sub(r'\W+', ' ', match.group(1))+"  <------>" +re.sub(r'\W+', ' ', match.group(2)))
re.sub(r'\W+', '', match.group(1))

理想情况下,我希望它遍历上面“target”列表中的每个元素,并提取短语的左右三个单词,这段代码就是这样做的,但前提是搜索词在正则表达式中是常量

提前谢谢


Tags: oftheintestrecitymosttarget