I'm taking a look at some parser combinator libraries in Python (Parsy to be more precise) and I'm currently faced with the following problem, simplified with a minimally working example below:
text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''
start, stop = r"STARTS?", r"STOPS?"
s = section(text, start, stop)
print(s)
which should output:
THE TEXT HERE SHOULD
BE CAPTURED
The current solution I'm working is by doing a regex lookahead, it works fine, but my original problem involves combining many of these little regexes, which can get messy and a problem for others to maintain later.
from typing import Pattern, TypeVar
import re
# A Generic type declaration.
T = TypeVar("T")
def first(text: str, pattern: str, default: T, flags=0) -> T:
"""
Given a `text`, a regex `pattern` and a `default` value, return the first match
in `text`. Otherwise return a `default` value if no match is found.
"""
match = re.findall(pattern, text, flags=flags)
return match[0] if len(match) > 0 else default
def section(text: str, begin: str, end: str) -> str:
"""
Given a `text` and two `start` and `stop` regexes, return the captured group
found in the interval. Otherwise, return an empty string if no match is found.
"""
return first(text, fr"{begin}([\s\S]*?)(?={end})", default="")
Parser Combinators seem to be perfect for situations like these, but I'm unable to reproduce the same behavior as the working solution, any hints would be welcome:
# A Simpler example with hardcoded stuff
from parsy import regex, seq, string
text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''
start = regex(r"STARTS?")
middle = regex(r"[\s\S]*").optional()
stop = regex(r"STOPS?")
eol = string("\n")
# Work fine
start.parse("START")
middle.parse("")
stop.parse("STOP")
section = seq(
start,
middle,
stop
)
# Simpler case, breaks
section.parse("START AAA STOP")
Gives:
---------------------------------------------------------------------------
ParseError Traceback (most recent call last)
<ipython-input-260-fdec112e1648> in <module>
24 )
25 # Simpler case, breaks
---> 26 section.parse("START AAA STOP")
~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse(self, stream)
88 def parse(self, stream):
89 """Parse a string or list of tokens and return the result or raise a ParseError."""
---> 90 (result, _) = (self << eof).parse_partial(stream)
91 return result
92
~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse_partial(self, stream)
102 return (result.value, stream[result.index:])
103 else:
--> 104 raise ParseError(result.expected, stream, result.furthest)
105
106 def bind(self, bind_fn):
ParseError: expected 'STOPS?' at 0:14
The issue is that the middle
parser matches the text until the end, so there is nothing for the stop
parser to consume:
seq(start, middle).parse("START AAA STOP")
prints
['START', ' AAA STOP']
One solution to avoid this behavior is to use the lookahead option for the middle
regex:
middle = regex(r"[\s\S]*(?=STOP)").optional()
This ensures that the matched text is followed by the "STOP" word.
Alternatively, you can use the should_fail
method from Parsy:
middle = (regex(r"STOPS?").should_fail("not STOP") >> any_char).many().concat()