Here's what I came up with:
import re
class Bunch(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
match = re.compile(
flags = re.VERBOSE,
pattern = r"""
( (?!with) (?P<first> [a-zA-Z_]+ ) )
( \s+ (?!with) (?P<second> [a-zA-Z_]+ ) )?
( \s+ (?P<awith> with ) )?
(?![a-zA-Z_\s]+)
| (?P<error> .* )
"""
).match
s = 'john doe with'
b = Bunch(**match(s).groupdict())
print 's:', s
if b.error:
print 'error:', b.error
else:
print 'first:', b.first
print 'second:', b.second
print 'with:', b.awith
Output:
s: john doe with
first: john
second: doe
with: with
Tried it also with:
s: john
first: john
second: None
with: None
s: john doe
first: john
second: doe
with: None
s: john with
first: john
second: None
with: with
s: john doe width
error: john doe width
s: with
error: with
BTW: re.VERBOSE and re.DEBUG are your friends.
Regards,
Mick.