python - 查找子字符串时正则表达式中的不平衡括号
问题描述
我正在尝试使用正则表达式,同时在字符串中查找不完整单词的子字符串
str1 = "a) John is working in Microsoft"
str2 = "a) John is wor"
预期答案:"a) John is working"
我尝试了简单的正则表达式:re.findall(r"(\S*" + str2+ r"\S*)", str1)
但它给出的错误Unbalanced Parenthesis
有人可以帮忙吗?
解决方案
这里的问题可能是字符串)
中的。str2
您可以str2
使用re.escape
以下方法解决此问题:
str1 = "a) John is working in Microsoft"
str2 = "a) John is wor"
matches = re.findall(r'(\S*' + re.escape(str2) + r'\S*)', str1)
print(matches)
这打印:
['a) John is working']
注意:您似乎已经交换str1
了str2
原始问题,所以我也修复了这个问题。
推荐阅读
- primefaces - 从命令按钮调用 Primefaces 对话框时不起作用
- powerapps - 如何在两个表之间进行连接并以相同的方式进行过滤?
- python - 迭代订单以捕获和组织时间值
- c++ - 是否可以将函数调用堆栈放在堆上?
- javascript - Eloquent javascript 第4章计算相关性
- laravel - 嵌套 foreach 循环以显示数据
- azure-devops - 从 VSTS 导出具有组和团队权限的用户列表
- postgresql - 将bytea转换为二进制字符串
- iis - IISHttpServer - 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme
- bazel - 在 bazel 构建系统中读取本地文件内容