[Tutor] Regular Expression Misunderstanding
Kent Johnson
kent37 at tds.net
Fri Jul 14 15:09:48 CEST 2006
Steve Nelson wrote:
> On 7/14/06, John Fouhy <john at fouhy.net> wrote:
>
>
>>>>> m = re.match(...)
>>>>> dir(m)
>>>>>
>> It will tell you what attributes the match object has.
>>
>
> Useful - thank you.
>
> I am now confuse on this:
>
> I have a file full of lines beginning with the letter "b". I want a
> RE that will return the whole line if it begins with b.
>
> I find if I do eg:
>
>
>>>> m = re.search("^b", "b spam spam spam")
>>>> m.group()
>>>>
> 'b'
>
> How do I get it to return the whole line if it begins with a b?
Use the match object in a test. If the search fails it will return None
which tests false:
for line in lines:
m = re.search(...)
if m:
# do something with line that matches
But for this particular application you might as well use
line.startswith('b') instead of a regex.
Kent
More information about the Tutor
mailing list