For example
string1 = "Hello this is the first string, it will be used in this project"
string2 = "Hello this is string2 and i will not be used in this project"
i want this script to return all matching expressions in string1 from string2
output should be : [Hello this is, will, be used in this project]
i've made a custom function to achieve this using a loop but i'm afraid it's too slow
Here is my custom function, i'm sure it's terrible in so many ways but i'm still learning python.
from re import search
fullstring = "Hello this is the first string, it will be used in this project"
substring = "Hello this is string2 and i will not be used in this project"
last_found_str = ""
#while string is not empty keep looping
while test_substring:
print("Searching for {}".format(test_substring))
#if substring in fullstring
if search(r'\b{}\b'.format(test_substring), fullstring):
print("Found! : {}".format(test_substring))
#add to list
phrases_list.append(test_substring)
#remove the found substring
substring = substring.replace(test_substring,'')
if substring == " ":
break
test_substring = substring
#this is the substring from the last found results
last_found_str = substring
else:
#if only one word is left
if len(test_substring.split()) == 1:
print("{} is not found".format(test_substring))
if len(last_found_str.split()) > 1:
#if substring from last found results is more than 1 word, remove the first word and loop through the rest
substring = substring.replace(r'\b{}\b'.format(test_substring),'')
test_substring = last_found_str.partition(' ')[2]
last_found_str = test_substring
else:
#if its a word or less then stop looping
break
else:
#if there is more than one word remove the last word and keep looping
test_substring = test_substring.rsplit(' ', 1)[0]
print(phrases_list)