Regular Expression question

L

looping

Hi,
It's not really a Python question but I'm sure someone could help me.

When I use RE, I always have trouble with this kind of search:

Ex.

I've a text file:
"""
create or replace package XXX
....

create or replace package body XXX
....
"""
now I want to search the position (line) of this two string.

for the body I use:
s = re.search(r'create\s+or\s+replace\s+package\s+body\s+', txt,
re.IGNORECASE)

but how to search for the other line ?
I want the same RE but explicitly without "body".

Thanks for your help.
 
M

Marc 'BlackJack' Rintsch

Hi,
It's not really a Python question but I'm sure someone could help me.

When I use RE, I always have trouble with this kind of search:

Ex.

I've a text file:
"""
create or replace package XXX
...

create or replace package body XXX
...
"""
now I want to search the position (line) of this two string.

for the body I use:
s = re.search(r'create\s+or\s+replace\s+package\s+body\s+', txt,
re.IGNORECASE)

but how to search for the other line ?
I want the same RE but explicitly without "body".

The write the same RE but explicitly without "body". But I guess I didn't
understand your problem when the answer is that obvious.

Maybe you want to iterate over the text file line by line and match or
search within the line? Untested:

needle = re.compile(r'create\s+or\s+replace\s+package(\s+body)?\s+',
re.IGNORECASE)
for i, line in enumerate(lines):
if needle.match(line):
print 'match in line %d' % (i + 1)

Ciao,
Marc 'BlackJack' Rintsch
 
L

looping

needle = re.compile(r'create\s+or\s+replace\s+package(\s+body)?\s+',
re.IGNORECASE)

What I want here is a RE that return ONLY the line without the "body"
keyword.
Your RE return both.
I know I could use it but I want to learn how to search something that
is NOT in the string using RE.
 
P

Peter Otten

looping said:
What I want here is a RE that return ONLY the line without the "body"
keyword.
Your RE return both.
I know I could use it but I want to learn how to search something that
is NOT in the string using RE.

You want a "negative lookahead assertion" then:
.... Isaac Asimov
.... Isaac Singer
.... """['Isaac Newton', 'Isaac Singer']

Peter
 
L

looping

You want a "negative lookahead assertion" then:

Now I feel dumb...
I've seen the (?!...) dozen times in the doc but never figure out that
it is what I'm looking for.

So this one is the winner:
s = re.search(r'create\s+or\s+replace\s+package\s+(?!body\s+)', txt,
re.IGNORECASE)

Thanks Peter and Marc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,607
Members
45,240
Latest member
pashute

Latest Threads

Top