Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #14418

Re: Question: Optional Regular Expression Grouping

Date 2011-10-10 23:49 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: Question: Optional Regular Expression Grouping
References <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.1872.1318287022.27778.python-list@python.org> (permalink)

Show all headers | View raw


On 10/10/2011 22:57, galyle wrote:
> HI, I've looked through this forum, but I haven't been able to find a
> resolution to the problem I'm having (maybe I didn't look hard enough
> -- I have to believe this has come up before).  The problem is this:
> I have a file which has 0, 2, or 3 groups that I'd like to record;
> however, in the case of 3 groups, the third group is correctly
> captured, but the first two groups get collapsed into just one group.
> I'm sure that I'm missing something in the way I've constructed my
> regular expression, but I can't figure out what's wrong.  Does anyone
> have any suggestions?
>
> The demo below showcases the problem I'm having:
>
> import re
>
> valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\
> [\']+.*$')
> line1 = "[field1][field2] = blarg"
> line2 = "    'a continuation of blarg'"
> line3 = "[field1][field2][field3] = blorg"
>
> m = valid_line.match(line1)
> print 'Expected: ' + m.group(1) + ', ' + m.group(2)
> m = valid_line.match(line2)
> print 'Expected: ' + str(m.group(1))
> m = valid_line.match(line3)
> print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2)

Instead of "\S" I'd recommend using "[^\]]", or using a lazy repetition
"\S+?".

You'll also need to handle the space before the "=" in line3.

valid_line = 
re.compile(r'^\[(\[^\]]+)\]\[(\[^\]]+)\](?:\s+|\[(\[^\]]+)\])\s*=|\s+[\d\[\']+.*$')

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Question:  Optional Regular Expression Grouping galyle <galyle@gmail.com> - 2011-10-10 14:57 -0700
  Re: Question:  Optional Regular Expression Grouping MRAB <python@mrabarnett.plus.com> - 2011-10-10 23:49 +0100
  Re: Question: Optional Regular Expression Grouping Vlastimil Brom <vlastimil.brom@gmail.com> - 2011-10-11 00:59 +0200
    Re: Question: Optional Regular Expression Grouping galyle <galyle@gmail.com> - 2011-10-10 16:24 -0700
  Re: Question: Optional Regular Expression Grouping Ian Kelly <ian.g.kelly@gmail.com> - 2011-10-10 17:03 -0600

csiph-web