为了账号安全,请及时绑定邮箱和手机立即绑定

查找子字符串时正则表达式中的括号不平衡

查找子字符串时正则表达式中的括号不平衡

至尊宝的传说 2023-07-18 16:36:15
我正在尝试使用正则表达式,同时查找字符串中单词不完整的子字符串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有人可以帮忙吗?
查看完整描述

2 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

这里的问题可能是字符串)中的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,所以我也解决了这个问题。


查看完整回答
反对 回复 2023-07-18
?
哔哔one

TA贡献1854条经验 获得超8个赞

你可以这样做。


str1 = "a) John is working in Microsoft"

str2 = "a) John is wor"


if str1.startswith(str2):

    print(str2 + str1[len(str2):].split(" ")[0])


else:

    print("it doesn't go")

这就是它打印的内容。


a) John is working


查看完整回答
反对 回复 2023-07-18
  • 2 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信