首页 > 解决方案 > 在python中将字符串变量转换为正则表达式

问题描述

我正在创建一个带有两个输入的 python 函数:一个文件和一个字符串,用户可以在其中找到字符串在文件中的位置。我认为最好的方法是使用正则表达式。我已经在代码的前面将文件转换为一个大字符串(file_string)。例如,假设用户想在文件中查找“hello”。

input = "hello"
user_input = "r'(" + input + ")'" 
regex = re.compile(user_input) 
for match in regex.finditer(file_string): 
    print(match.start()) 

在输入变量周围创建带有 r' ' 的新字符串不起作用。但是,如果我将 user_input 替换为 r'hello',则代码可以完美运行。如何将用户输入的字符串输入转换为可以放入 re.compile() 的表达式?

提前致谢。

标签: pythonregex

解决方案


r只是原始字符串文字语法的一部分,可用于简化一些正则表达式。例如,"\\foo"r'\foo'产生相同的str对象。它不是字符串本身值的一部分。

您需要做的就是创建一个值为inputbetween(和的字符串)

input = "hello"
user_input = "(" + input + ")" 

更有效(如果只是稍微如此)

user_input = "({})".format(input)

或者在最新版本的 Python 中更简单:

user_input = f'({input})'

推荐阅读