python - 在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() 的表达式?
提前致谢。
解决方案
这r
只是原始字符串文字语法的一部分,可用于简化一些正则表达式。例如,"\\foo"
并r'\foo'
产生相同的str
对象。它不是字符串本身值的一部分。
您需要做的就是创建一个值为input
between(
和的字符串)
。
input = "hello"
user_input = "(" + input + ")"
更有效(如果只是稍微如此)
user_input = "({})".format(input)
或者在最新版本的 Python 中更简单:
user_input = f'({input})'
推荐阅读
- html - justify-content 和 align-items 在使用显示时无法正常工作:flex
- amazon-web-services - 部署期间ECS服务中的所需任务计数
- c# - 为什么在非托管错误中出现堆栈溢出异常
- android - Android Studio IDE 显示未解析的引用/忽略导入,而构建很好
- php - 嗨,我想通过从数据库中获取来限制循环中的 flexi 滑块图像,我的项目在 codeignitor 中
- spring-boot - 应用程序在 Eureka 中注册失败,抛出 404 null 错误
- css - 图像无响应并溢出 Wordpress 中的容器
- java - PDF 文档的数字签名
- javascript - 在Electron,javascript中更改保存对话框的默认路径
- laravel - Laravel 密码过期,类不存在