[Tutor] regex question
Wayne Werner
waynejwerner at gmail.com
Tue Jan 4 16:55:37 CET 2011
On Tue, Jan 4, 2011 at 9:37 AM, Richard D. Moores <rdmoores at gmail.com>wrote:
> I use
>
> regex = ".*" + search + ".*"
> p = re.compile(regex, re.I)
>
> in finding lines in a text file that contain search, a string entered
> at a prompt.
>
> What regex do I use to find lines in a text file that contain search,
> where search is a word entered at a prompt?
>
> Thanks,
>
> Dick Moores
You could use (2.6+ I think):
word = raw_input('Enter word to search for: ')
with open('somefile.txt') as f:
for line in f:
if word in line:
print line
You could always try a speed test, but I'm guessing that other than
extremely large files (10k+ lines) you probably won't see much speed
difference. Then again, you might!
HTH,
Wayne
p.s. I tend to only use a regex when I absolutely need to, because usually
when you try to solve one problem with a regex it becomes two problems.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110104/1de9d0d8/attachment.html>
More information about the Tutor
mailing list