PyPE - Python Parsing Expressions Library (API)¶
The Pattern Base Class¶
Pattern is an abstract base class for all pattern
objects. The most important function for patterns is
match(string[, index]), which checks
a string starting at the given index to see if it matches the pattern. A
Match object is returned if a match is found, or
None if the pattern did not match the string at the given index. Each
subclass of Pattern implements different search
patterns. Note that for convenience the pattern object can be called as if it
is a function, and the call is forwarded to match(). Therefore, if
ptn is a pattern, the following are equivalent:
>>> match = ptn.match("This is a test")
>>> match = ptn("This is a test")
A Match object allows you to get the string that
was matched and any captures. It also includes a context value that
provides access to any Stack objects that were created. Some patterns
may succeed without consuming any values from the string. Some care must be
taken to ensure that no recursive expressions occur that consume no input to
avoid infinite loops. For reference, this is referred to as “left recursion”
in PEG literature, and grammars can be rewritten to remove “left recursion”.
Information on this can be found via an internet search.
Any pattern can be ‘named’ by calling setName
for the pattern or by using the ‘set name’ operator (shown later). This is
primarily used for debugging purposes or when building a Tokenizer,
since all token patterns must have a name specified.
Debug mode can be set for any pattern by calling the function
debug with True (to debug all subpatterns),
False (to supress debug message for a pattern and subpatterns]), and
"named" (to show only named patterns in the debug output).
Pattern¶
- class PyPE.PyPE.Pattern¶
Abstract base class for all parsing expression patterns.
- debug(debugOpt=None, **args)¶
Set or return the debug options for this pattern. The basic options that can be set are:
True or ‘show’ to show parsing debug information for the current pattern and all contained patterns.
False or ‘hide’ to suppress debug information for the current pattern and all contained patterns.
‘named’ to show parsing debug information for any named patterns contained within the current pattern.
Other options may be added. For the available options, see the
DebugOptionsclass constructor which is called with the parameters sent to this function.When the debug option is set to True, pattern results are printed to the console by default. The output source can be modified via a custom
DebugOptionsobject.When the debug option is set to ‘show’, ‘hide’, or ‘named’, the option applies to any contained patterns that do not have some other other explicitly set.
- Parameters:
debugOpt – This option can be an object that implements the beforeMatch and afterMatch functions with signatures that match the DebugOptions functions of the same name. If this is True or ‘show’, debugging is enabled. If this is False or ‘hide’, debugging is disabled. If this is ‘named’, only named patterns are shown. If this is ‘show_only_success’, only successful matches are shown. If this is a function, it is used as a DebugOptions afterMatch filter.
**args – If more control is needed, arguments can be passed in that are forwarded to the DebugOptions constructor. See the constructor for more details.
- Returns:
When no options are passed in, this returns the debug options object for this Pattern. If parameters are passed in, a DebugOptions object is created and associated with this Pattern.
The debug option can be set using:
>>> p = P(1).debug(True) >>> p = P(1) & 'show' # Same as True >>> p = 'hide' & P(1) # Same as False
- match(string, index=0, context=None)¶
Match the Pattern against the string starting at the given index. Note that
Patternimplements the __call__ method which forwards calls to this function.- Parameters:
string – A string to match.
index – The location in the string to look for the given pattern.
context – Store stack information and information that is passed forward during match operations.
- Returns:
A
Matchobject if the pattern succeeds, or None if the pattern fails.
>>> p = P('t') # Match the 't' character >>> p.match('test') t >>> p('test') # Equivalent to call above t
- setName(name)¶
Set the name for a pattern object. When debugging, the name is printed in the debugging output in place of the Pattern specification. It is also used by the
Tokenizerclass.- Parameters:
name – The name for the Pattern.
- Returns:
The Pattern object. Allows chaining of commands.
>>> p = P(1).setName('test 1') >>> p.name 'test 1' >>> p = 'test 2' | P(1) >>> p.name 'test 2' >>> p = P(1) | 'test 3' >>> p.name 'test 3'
Pattern Operators¶
P (Pattern)¶
- class PyPE.P(value)¶
The Pattern class matches a literal string or a specific number characters or checks against a user defined matcher function or matches against another Pattern.
- static asPattern(pattern)¶
If item is a pattern, return the pattern. Otherwise return P(pattern)
- static isValidValue(value, msg='Invalid arg for P(arg)')¶
Verify that P(arg) is a valid arg. Raise an exception if not.
- match(string, index=0, context=None)¶
Match the given pattern :param context:
- match_TF(string, index=0, context=None)¶
Return False if the value is False, or the ‘index’ value if not past end of string.
>>> p = P(False) >>> p("test") is None True >>> p = P(True) >>> p("test") == "" True >>> p("test",3) == "" True
- match_fn(string, index=0, context=None)¶
Call the function with signature:
match = fn(string, index, context)
The function can return one of the following:
A match object
An integer between index and the length of the string. This results in a match object ending at the given integer.
True results in a match object beginning and ending at the current index
False or any value not matching the above results in a match value of None.
>>> p = P(lambda str, i, ctxt: i+2) >>> p("test") te >>> p("test",3) is None True >>> p = P(lambda str, i, ctxt: True) >>> p("test",4) == "" True
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- match_n(string, index=0, context=None)¶
Matches exactly n characters.
>>> p = P(1) >>> p("") is None True >>> p("a") a >>> p = P(3) >>> p("ab") is None True >>> p("abc") abc >>> p("abc",1) is None True
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- match_neg(string, index=0, context=None)¶
Matches less than n characters only (end of string).
>>> p = P(-3) >>> p("") == "" True >>> p("ab") ab >>> p("abc") is None True
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- match_ptn(string, index=0, context=None)¶
Matches the pattern passed in.
>>> p = P(P("ab")) >>> p("abba") ab >>> p("abba",1) is None True
- match_str(string, index=0, context=None)¶
Matches an exact string.
>>> p = P("test") >>> p("testing") test >>> p("A test",2) test >>> p("Failed") is None True
I (Ignore Case)¶
- class PyPE.I(string)¶
Match case insensitive string.
- match(string, index=0, context=None)¶
Match case insensitive string.
>>> p = I("AcE") >>> p("Ace") Ace >>> p("ACE") ACE >>> p("ace") ace
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
S (Set)¶
- class PyPE.S(set)¶
Match any of a given set of characters.
- match(string, index=0, context=None)¶
Match character in the given set.
>>> p = S("ace") >>> p("a") a >>> p("b") is None True >>> p("abc",2) c
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
R (Range)¶
- class PyPE.R(*ranges)¶
Match characters in any of the given ranges. Each range is comprised of two characters where the ascii value of a character must be within the range of the two characters to be a match. Any number of ranges can be specified within the range object.
- match(string, index=0, context=None)¶
Matches any character in the given set of ranges.
>>> p = R("AZ","az") >>> p("a") a >>> p("Q") Q >>> p("1") is None True
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
SOL (Start of Line)¶
- class PyPE.SOL¶
Check if his is the Start of Line (SOL).
- match(string, index=0, context=None)¶
Match the start of a line.
- Parameters:
context –
string – The string to match
index – The index to start at
- Returns:
A match object. No characters are consumed.
>>> p = SOL() >>> p.match("test\n123\n") == "" True >>> p.match("test\n123\n",1) is None True >>> p.match("test\n123\n",5) == "" True >>> p.match("test\n123\n",6) is None True >>> p.match("test\n123\n",9) == "" True
EOL (End of Line)¶
- class PyPE.EOL¶
Detect whether the current position is at the end of a line.
- match(string, index=0, context=None)¶
Detect whether the current position is at the end of a line.
- Parameters:
context –
string – The string to compare against
index – The location to check.
- Returns:
A match object that consumes no input.
>>> p = EOL() >>> p.match("") == "" True >>> p.match(" \r\n",2) is None True >>> p.match(" \r\n",3) == "" True >>> p.match(" \r\n",4) is None True >>> p.match("\n",0) == "" True
Capture Operators¶
C (Capture)¶
- class PyPE.C(pattern)¶
Capture a pattern
- getPatterns()¶
Get the pattern associated with this group capture :return: The contained pattern in a list
- match(string, index=0, context=None)¶
Add a Pattern match to the list of Captures.
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
>>> p = C(C(P(2))*P(1)) >>> match = p("abcd") >>> match.getCapture(0) 'abc' >>> match.getCapture(1) 'ab'
Cb (Backcapture)¶
- class PyPE.Cb(name, pattern=None, captureIndex=None)¶
Backcapture
- getPatterns()¶
Get the pattern associated with this group capture :return: The contained pattern in a list
- match(string, index=0, context=None)¶
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
>>> p = Cb("test",P("cat")+P("dog")) * P(" ") * Cb("test") >>> p.match("dog dog") dog dog >>> p.match("cat cat") cat cat >>> p.match("cat dog") == None True >>> p = Cb("quote", S("\"'")) * C((1-Cb("quote"))**0) * Cb("quote") >>> p.match("'Matched quoted string' but not extra stuff").captures[0] 'Matched quoted string' >>> p.match('"Quoted String" without extra stuff').captures[0] 'Quoted String'
Cc (Contstant Capture)¶
- class PyPE.Cc(value)¶
Capture a constant value.
- match(string, index=0, context=None)¶
Capture the specified value.
>>> p = Cc("test") >>> match = p("") >>> match[0] 'test'
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
Cg (Group Capture)¶
- class PyPE.Cg(pattern)¶
Group and contained Captures into a single capture. If there are no captures, the single capture will be an empty array.
- getPatterns()¶
Get the pattern associated with this group capture :return: The contained pattern in a list
- match(string, index=0, context=None)¶
Group the contained captures into a single capture.
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- Examples:
>>> p = Cg(C(P(1)) * C(P(1))) >>> p("Test").getCapture(0) ['T', 'e'] >>> p("b") is None True
Cs (Stack Capture)¶
- class PyPE.Cs(stack, n=1, pop_from_stack=False)¶
Capture values from a stack
- match(string, index=0, context=None)¶
Capture values from a stack
- Parameters:
string – The string to match against.
index – The current location in the string.
context – Information that is forwarded between matches.
- Returns:
A match object stack values added as captures.
- Examples:
>>> p = Sc('test',Cc('1')*Cc('2')*Cc('3')) * Cs('test') >>> match = p.match("") >>> match.captures ['3'] >>> match.context.getStack('test')[0:] ['1', '2', '3']
>>> p = Sc('test',Cc('1')*Cc('2')*Cc('3')) * Cs('test', 2, pop_from_stack=True) >>> match = p.match("") >>> match.captures ['2', '3'] >>> match.context.getStack('test')[0:] ['1']
Cl (Line number Capture)¶
- class PyPE.Cl¶
Capture the current line number.
- match(string, index=0, context=None)¶
Capture the line number at the given index.
- Parameters:
string – The string to match against
index – The index for which to get the line number
context – Information that is forwarded between matches.
- Returns:
A match object with the line number added to the captures
- Example:
>>> p = Cl() >>> p("\n\n\n\n\n\n\n\n",3).getCapture(0) 4
Cp (Position Capture)¶
- class PyPE.Cp¶
Capture the current position.
- match(string, index=0, context=None)¶
Capture the current position in the string (index value).
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
>>> p = Cp() >>> p("test",3).getCapture(0) 3 >>> p("test",1).getCapture(0) 1
Col (Column Capture)¶
- class PyPE.Col¶
Capture the column (distance since last newline).
- match(string, index=0, context=None)¶
Capture the column for the current index (distance past last newline)
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- Returns:
A match object that consumes no characters, but adds a column capture.
>>> p = Col() >>> # 0 123 456789 >>> # 012345 >>> p.match("\n \n Test",9).getCapture(0) 5
Stack Operators¶
Sc (Capture to Stack)¶
- class PyPE.Sc(stack, pattern)¶
Move captures to the specified stack in the context.
- getPatterns()¶
Get the pattern associated with this group capture :return: The contained pattern in a list
- match(string, index=0, context=None)¶
Move the captured values to the specified stack.
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- Returns:
A match object that consumes no characters, but adds a column capture.
- Example:
>>> p = Sc('test',Cc('one')*Cc('two')) >>> match = p.match("") >>> match.context.getStack('test')[0:] ['one', 'two']
Sm (Stack Match)¶
- class PyPE.Sm(stack, n=-1, expected=None)¶
Match a value in the Stack with one in the string passed to match, or check for a specific string on the match stack. Checking for a specific string on the stack at a given location is useful for controling the parsing logic based on state stored on the stack.
- match(string, index=0, context=None)¶
Match value on the stack.
- Parameters:
string – The string to match.
index – The location in string to start match.
context – Information that is forwarded between matches.
- Returns:
A match object that consumes no characters, but adds a column capture.
- Example:
>>> p = Sc("my_stack",Cc("test")*Cc("ing"))*Sm("my_stack",0)*Sm("my_stack") >>> p("testing") testing >>> p("tester") == None True
>>> p = Sc("items",Cc("one")*Cc("two"))*Sm("items",0,"one")*Sm("items",1,"two") >>> match = p('') >>> isinstance(match, Match) True
Ssz (Stack Size)¶
- class PyPE.Ssz(stack, n=None)¶
Get the stack size or match only if it has a given size
- match(string, index=0, context=None)¶
Capture the stack size or check that the stack matches a given size.
- Parameters:
string – The string to match
index – The location in string to start match
context – Information that is forwarded between matches.
- Returns:
A match object that consumes no characters, but adds a column capture.
Match Objects¶
A Match object is returned when the match(string, index)
function for a pattern is called with a string, and the string matches the
pattern at the given index. The Match object indicates the portion of the
string that was matched, the start and end location of the match, and contains
any captures from the pattern.
Match¶
- class PyPE.PyPE.Match(string, start, end=None)¶
The
Matchobject tracks the text that was matched by a PEG pattern, and provides access to any match captures.- Variables:
string – The original string that was matched.
start – The location in the string where the pattern match starts.
end – The location in the string where the pattern match ends.
captures – The Pattern captures. Note that the
match.getCapture(n)method is available to access captures, or simplymatch[n].len(match)indicates the number of captures.
- getCapture(index)¶
Get the capture at the specified index. If the index does not exist, throw an IndexError. Note that the number of captures for a Match object named
matchis given bylen(match). Note that array syntax can be used with the Match object as a shorthand for calling this method. For example,match[1]is equivalent tomatch.getCapture(1).- Parameters:
index – The index of the capture with the first capture being index 0. A negative index is used to access values relative to the end of the array, with index -1 being the last capture value.
- Returns:
The requested capture value.
- getValue(default=None)¶
Get the string that was matched by the PEG pattern.
- hasCaptures()¶
- Returns:
Return true if this Match object contains any captures.