Regular expression query

bruno at modulix onurb at xiludom.gro
Fri Feb 3 10:41:33 EST 2006


Martin Biddiscombe wrote:
> It's probably quite simple, but what I want is a regular expression

If it's simple, then you probably *dont* want a regexp.

> to
> parse strings of the form:
> 
> "parameter=12ab"
> "parameter=12ab foo bar"
> "parameter='12ab'"
> "parameter='12ab' biz boz"
> "parameter="12ab""
> "parameter="12ab" junk"
> 
> in each case returning 12ab as a match. "parameter" is known and fixed.
> The parameter value may or may not be enclosed in single or double
> quotes, and may or may not be the last thing on the line. If the value
> is quoted, it may contain spaces.
> 
> I've tried a regex of the form:
> re.compile(r'parameter=(["\']?(.*?)\1( *|$)')
> 
> This works fine when the parameter's value is quoted, but if the quotes
> are missing, it falls over since the \1 is empty and so the non-greedy
> "match anything" ends up matching nothing.
> 
> Any suggestions?

yes : forget regexps, use str methods.

parse = lambda l: \ l.split('=',1)[1].split()[0].strip().strip("'\"")

NB : I tried my best to make it as obfuscated as a regexp so you still
gain extra bonus points from Perl-addicts !-p - but feel free to rewrite
this cleanly.


> Thanks

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list