我正在嘗試使用正則表達式,同時查找字符串中單詞不完整的子字符串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,所以我也解決了這個問題。

嗶嗶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
添加回答
舉報
0/150
提交
取消