首页 > 解决方案 > 查找子字符串时正则表达式中的不平衡括号

问题描述

我正在尝试使用正则表达式,同时在字符串中查找不完整单词的子字符串

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

有人可以帮忙吗?

标签: pythonregex

解决方案


这里的问题可能是字符串)中的。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']

注意:您似乎已经交换str1str2原始问题,所以我也修复了这个问题。


推荐阅读