How can I exclude a word by using re?

John Machin sjmachin at lexicon.net
Mon Aug 15 08:09:12 EDT 2005


could ildg wrote:
> In re, the punctuation "^" can exclude a single character, but I want
> to exclude a whole word now. for example I have a string "hi, how are
> you. hello", I want to extract all the part before the world "hello",
> I can't use ".*[^hello]" because "^" only exclude single char "h" or
> "e" or "l" or "o". Will somebody tell me how to do it? Thanks.

(1) Why must you use re? It's often a good idea to use string methods 
where they can do the job you want.
(2) What do you want to have happen if "hello" is not in the string?

Example:

C:\junk>type upto.py
def upto(strg, what):
     k = strg.find(what)
     if k > -1:
         return strg[:k]
     return None # or raise an exception

helo = "hi, how are you? HELLO I'm fine, thank you hello hello hello. 
that's it"

print repr(upto(helo, "HELLO"))
print repr(upto(helo, "hello"))
print repr(upto(helo, "hi"))
print repr(upto(helo, "goodbye"))
print repr(upto("", "goodbye"))
print repr(upto("", ""))

C:\junk>upto.py
'hi, how are you? '
"hi, how are you? HELLO I'm fine, thank you "
''
None
None
''

HTH,
John



More information about the Python-list mailing list