Question about metacharacter '*'

MRAB python at mrabarnett.plus.com
Sun Jul 6 11:32:26 EDT 2014


On 2014-07-06 13:09, Devin Jeanpierre wrote:
> On Sun, Jul 6, 2014 at 4:51 AM,  <rxjwg98 at gmail.com> wrote:
>> Hi,
>>
>> I just begin to learn Python. I do not see the usefulness of '*' in its
>> description below:
>>
>>
>>
>>
>> The first metacharacter for repeating things that we'll look at is *. * doesn't
>> match the literal character *; instead, it specifies that the previous character
>> can be matched zero or more times, instead of exactly once.
>>
>> For example, ca*t will match ct (0 a characters), cat (1 a), caaat (3 a
>> characters), and so forth.
>>
>>
>>
>> It has to be used with other search constraints?
>
> (BTW, this is a regexp question, not really a Python question per se.)
>
> That's usually when it's useful, yeah. For example, [0-9] matches any
> of the characters 0 through 9. So to match a natural number written in
> decimal form, we might use the regexp [0-9][0-9]*, which matches the
> strings "1", "12", and "007", but not "" or "Jeffrey".
>
> Another useful one is `.*` -- `.` matches exactly one character, no
> matter what that character is. So, `.*` matches any string at all.
>
Not quite. It won't match a '\n' unless the DOTALL flag is turned on.

> The power of regexps stems from the ability to mix and match all of
> the regexp pieces in pretty much any way you want.
>




More information about the Python-list mailing list