[Gllug] matching strings in python

Stuart Sears stuart at sjsears.com
Sun Oct 2 09:33:38 UTC 2011


On 02/10/11 09:36, dudes dudes wrote:
> Hello,
> 
> Can someone kindly point me my mistake here in this code. I'm trying to
> search a file for 10000 OR 10001 (in python).
> 
> import re;
> 
> this= open("file", r)
> for line in this:
>    if re.match('(10000)' | '(10001)', line)
>         print line

RTFM :)

http://docs.python.org/library/re.html#matching-vs-searching

specifically:
where are these numbers on each line? Are they at the start? if not,
re.match won't find them without a preceding wildcard.

Also, there's no need for the 'this=...' bit, unless you actually feel
you need the variable.

Something like the following

for line in open('filename'):
    if re.search('1000[01]', line):
        print line

is more likely to succeed


> /*It doesn't give me any errors. However; doesn't find the 10000 OR 10001 */
As Tet says, that's difficult to credit, unless you have selectively
copied and pasted random bits of your code into this email and changed
the quoting. Or just attempted to write it in email from memory.

At the very least:

* the 'r' on your open(...) line is not quoted.

* The re.match line itself will throw at least one syntax error - all
characters in your pattern should be inside one set of quotes.

* The second if statement is missing a colon.

This example was fairly trivial, but if you are asking for help with
code like this, it would help if you actually post working excerpts from
it. Or excerpts that throw the errors you are asking about.

Regards,

Stuart
-- 
Stuart Sears RHCA etc.
"It's today!" said Piglet.
"My favourite day," said Pooh.
--
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list