Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #74054
| References | <93a40570-00ed-4507-aa16-221d7e500468@googlegroups.com> |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Date | 2014-07-06 13:26 -0600 |
| Subject | Re: How to write this repeat matching? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.11559.1404675307.18130.python-list@python.org> (permalink) |
On Sun, Jul 6, 2014 at 12:57 PM, <rxjwg98@gmail.com> wrote:
> I write the following code:
>
> .......
> import re
>
> line = "abcdb"
>
> matchObj = re.match( 'a[bcd]*b', line)
>
> if matchObj:
> print "matchObj.group() : ", matchObj.group()
> print "matchObj.group(0) : ", matchObj.group()
> print "matchObj.group(1) : ", matchObj.group(1)
> print "matchObj.group(2) : ", matchObj.group(2)
> else:
> print "No match!!"
> .........
>
> In which I have used its match pattern, but the result is not 'abcb'
You're never going to get a match of 'abcb' on that string, because
'abcb' is not found anywhere in that string.
There are two possible matches for the given pattern over that string:
'abcdb' and 'ab'. The first one matches the [bcd]* three times, and
the second one matches it zero times. Because the matching is greedy,
you get the result that matches three times. It cannot match one, two
or four times because then there would be no 'b' following the [bcd]*
portion as required by the pattern.
>
> Only matchObj.group(0): abcdb
>
> displays. All other group(s) have no content.
Calling match.group(0) is equivalent to calling match.group without
arguments. In that case it returns the matched string of the entire
regular expression. match.group(1) and match.group(2) will return the
value of the first and second matching group respectively, but the
pattern does not have any matching groups. If you want a matching
group, then enclose the part that you want it to match in parentheses.
For example, if you change the pattern to:
matchObj = re.match('a([bcd]*)b', line)
then the value of matchObj.group(1) will be 'bcd'
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
How to write this repeat matching? rxjwg98@gmail.com - 2014-07-06 11:57 -0700
Re: How to write this repeat matching? MRAB <python@mrabarnett.plus.com> - 2014-07-06 20:19 +0100
Re: How to write this repeat matching? Ian Kelly <ian.g.kelly@gmail.com> - 2014-07-06 13:26 -0600
Re: How to write this repeat matching? rxjwg98@gmail.com - 2014-07-07 06:30 -0700
Re: How to write this repeat matching? Anssi Saari <as@sci.fi> - 2014-07-07 18:48 +0300
Re: How to write this repeat matching? Ian Kelly <ian.g.kelly@gmail.com> - 2014-07-07 10:18 -0600
csiph-web