How can I exclude a word by using re?
sjmachin at lexicon.net
Mon Aug 15 14:09:12 CEST 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?
def upto(strg, what):
k = strg.find(what)
if k > -1:
return None # or raise an exception
helo = "hi, how are you? HELLO I'm fine, thank you hello hello hello.
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("", ""))
'hi, how are you? '
"hi, how are you? HELLO I'm fine, thank you "
More information about the Python-list