Я предполагаю, что это простое выражение может просто сделать это
.*?(\b(?:to|for|with)\b.*)
и re.match
могут быть самыми быстрыми из этих пяти методов:
Тест с re.findall
import re
regex = r".*?(\b(?:to|for|with)\b.*)"
test_str = "I wish to check my python code for errors to run the program properly with fluency"
print(re.findall(regex, test_str))
Тест с re.sub
import re
regex = r".*?(\b(?:to|for|with)\b.*)"
test_str = "I wish to check my python code for errors to run the program properly with fluency"
subst = "\\1"
result = re.sub(regex, subst, test_str)
if result:
print (result)
Тест с re.finditer
import re
regex = r".*?(\b(?:to|for|with)\b.*)"
test_str = "I wish to check my python code for errors to run the program properly with fluency"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
# FULL MATCH
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
Тест с re.match
import re
regex = r".*?(\b(?:to|for|with)\b.*)"
test_str = "I wish to check my python code for errors to run the program properly with fluency"
print(re.match(regex, test_str).group(1))
Тест с re.search
import re
regex = r".*?(\b(?:to|for|with)\b.*)"
test_str = "I wish to check my python code for errors to run the program properly with fluency"
print(re.search(regex, test_str).group(1))
Выражение объяснено в верхней правой части этой демонстрации , если вы хотите исследовать или изменить его дальше, а в этой ссылке вы можете посмотреть, как она будет соответствовать против некоторых входных данных, если хотите.