Creates and returns a PEG pattern from a given parameter.
For a given parameter:
* literal string - Matches its specific text (case insensitively) in a
subject string.
* list - Must contain a single string which is treated as a character class,
otherwise a ``ValueError`` will be raised.
Matches any character in a subject string contained in this class.
* integer - Must be positive or a ``ValueError`` will be raised.
Matches exactly that many characters in a subject string.
* function - The function will be passed the subject string and current
index the PEG is at. If a non-negative integer is returned,
that integer becomes the new index, indicating a match.
* dictionary - A dictionary is interpreted as a grammar. These are useful
for defining recursive patterns. Each dictionary has key
names with pattern values, otherwise a ``TypeError`` will be
raised. Also, there must be a 'default' key whose value is
the name key for the default pattern to initially match. A
``ValueError`` will be raised if it does not exist. If it
points to an invalid name key, ``KeyError`` will be raised.
* Pattern - The pattern is simply copied.
* anything else - ``TypeError`` will be raised.
Warning: left-recursive patterns are not checked for and will cause a
``RuntimeError`` when ``match`` is called due to a recursion overflow.
Examples::
# creates a pattern that matches 'foo' literally
patt = Pattern('foo')
# creates a pattern that matches 'a', or 'b', or 'c' character once
patt = Pattern(['abc'])
# creates a pattern that matches any single character
patt = Pattern(1)
# creates a pattern that matches any even, single digit number
def even_single_digit(subject, index):
digit = subject[index]
if digit >= '0' and digit <= '9' and int(digit) % 2 == 0:
return index + 1
patt = Pattern(even_single_digit)
# creates a pattern that searches for 'e'
patt = Pattern({
1: Pattern('e') | Pattern(1) + PatternBackRef(1),
'default': 1
})
- Overrides:
Pattern.__init__
- (inherited documentation)
|