summaryrefslogtreecommitdiff
path: root/pyparsing/core.py
diff options
context:
space:
mode:
authorptmcg <ptmcg@austin.rr.com>2022-05-18 23:44:36 -0500
committerptmcg <ptmcg@austin.rr.com>2022-05-18 23:44:36 -0500
commitdbe71461b5a56967ff0abf79ce7c8b0eddb75a66 (patch)
treed1a597f9dc7562badc327b31d983dc7c2fbdf045 /pyparsing/core.py
parent8195b5650a647e7449aecd2e898ab7d0bb1ca6ed (diff)
downloadpyparsing-git-dbe71461b5a56967ff0abf79ce7c8b0eddb75a66.tar.gz
Add support for slice in expr[] notation, to pass stop_on repetition sentinel
Diffstat (limited to 'pyparsing/core.py')
-rw-r--r--pyparsing/core.py20
1 files changed, 20 insertions, 0 deletions
diff --git a/pyparsing/core.py b/pyparsing/core.py
index 13ff51b..4638d19 100644
--- a/pyparsing/core.py
+++ b/pyparsing/core.py
@@ -1639,8 +1639,23 @@ class ParserElement(ABC):
Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception
if more than ``n`` ``expr``s exist in the input stream. If this behavior is
desired, then write ``expr[..., n] + ~expr``.
+
+ For repetition with a stop_on expression, use slice notation:
+
+ - ``expr[...: end_expr]`` and ``expr[0, ...: end_expr]`` are equivalent to ``ZeroOrMore(expr, stop_on=end_expr)``
+ - ``expr[1, ...: end_expr]`` is equivalent to ``OneOrMore(expr, stop_on=end_expr)``
+
"""
+ stop_on_defined = False
+ stop_on = NoMatch()
+ if isinstance(key, slice):
+ key, stop_on = key.start, key.stop
+ stop_on_defined = True
+ elif isinstance(key, tuple) and isinstance(key[-1], slice):
+ key, stop_on = (key[0], key[1].start), key[1].stop
+ stop_on_defined = True
+
# convert single arg keys to tuples
try:
if isinstance(key, str_type):
@@ -1658,6 +1673,11 @@ class ParserElement(ABC):
# clip to 2 elements
ret = self * tuple(key[:2])
+ ret = typing.cast(_MultipleMatch, ret)
+
+ if stop_on_defined:
+ ret.stopOn(stop_on)
+
return ret
def __call__(self, name: str = None) -> "ParserElement":