我的猜测是,这个简单的表达式可能会简单地做到这一点
.*?(\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))
表达式在this demo 的右上角进行了解释,如果您想进一步探索或修改它,如果您愿意,可以在this link 中查看它如何与一些示例输入匹配。