首页 > 解决方案 > How to convert variable to a regex string?

问题描述

I am working in python I am looping through a large group of strings and I want to be able to see if they are in a second list of strings.

for line in dictionary:
    line = line.replace('\r\n','').replace('\n','')
    for each in complex8list:
        txt = re.compile(.*line.*)
        if re.search(each, txt):

I need to be able to check if the string with anything before it, and anything after it is in the second list.

What is the correct syntax to do this?

标签: pythonregex

解决方案


如果line不是正则表达式,您甚至不需要正则表达式。

if line in each:

如果line是一个正则表达式,那么你不需要做任何事情,因为前导.*是隐含的,re.search而尾随.*是不必要的。

if re.search(line, each):

顺便说一句,您似乎有re.search倒退的论据。


推荐阅读