-3

I am trying to use regex while finding substring with incomplete words in string

str1 = "a) John is working in Microsoft"

str2 = "a) John is wor"

Expected answer : "a) John is working"

I tried simple regex : re.findall(r"(\S*" + str2+ r"\S*)", str1)

But its giving error Unbalanced Parenthesis

Can someone help?

2 Answers2

0

The issue here likely is the ) in the str2 string. You may wrap str2 with re.escape to get around this problem:

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)

This prints:

['a) John is working']

Note: You appear to have swapped str1 and str2 in your original question, so I fixed that as well.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can do it like this.

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")

This is what it prints.

a) John is working
Yaga
  • 56
  • 2