Regular expression help: unable to search ' # ' character in the file

dudeja.rajat at gmail.com dudeja.rajat at gmail.com
Sat Sep 27 09:49:51 EDT 2008


On Sat, Sep 27, 2008 at 1:58 PM, Fredrik Lundh <fredrik at pythonware.com>wrote:

> dudeja.rajat at gmail.com wrote:
>
>  import re
>>
>> fd = open(file, 'r')
>> line = fd.readline
>> pat1 = re.compile("\#*")
>>            while(line):
>>                mat1 = pat1.search(line)
>>                if mat1:
>>                    print line
>>                    line = fd.readline()
>>
>
> I strongly doubt that this is the code you used.
>
>  But the above prints the whole file instead of the hash lines only.
>>
>
> "*" means zero or more matches.  all lines is a file contain zero or more #
> characters.
>
> but using a RE is overkill in this case, of course.  to check for a
> character or substring, use the "in" operator:
>
>    for line in open(file):
>        if "#" in line:
>            print line
>
> </F>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Thanks Fredrik, this works. Indeed  it is a much better and cleaner
approach.

-- 
Regards,
Rajat
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/0836ddfd/attachment-0001.html>


More information about the Python-list mailing list