Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
re.sub() solution in Clear category for Between Markers by martin.pilka
"""
"Atomic groups basically discards/forgets the subsequent tokens in the group once a token matches":
https://stackoverflow.com/questions/2973436/regex-lookahead-lookbehind-and-atomic-groups
With Atomic group, one can do:
(?>
|^) - If you can match
, use it and do not try other alternatives
Python does not support Atomic Groups yet:
https://stackoverflow.com/questions/13577372/do-python-regular-expressions-have-an-equivalent-to-rubys-atomic-grouping
Once supported, following would be possible (code not tested):
return re.search(f'(?>{re.escape(begin)}|^)(.*)(?>{re.escape(end)}|$)', text).group(2)
Until then, let's use re.sub() version.
"""
def between_markers(text: str, begin: str, end: str) -> str:
import re
# Handle special case when Begin marker comes after End marker
if begin in text and end in text and text.find(begin) > text.find(end):
return ''
# Replace Begin and End markers (if they are present)
return re.sub(f'^.*{re.escape(begin)}|{re.escape(end)}.*$', '', text)
Dec. 29, 2018
Comments: