正则表达式删除最后一个单词,如果它包含一个字符

时间:2012-12-06 11:19:03

标签: python regex

我需要Python中的一个正则表达式,它会删除字符串中的最后一个单词,如果它包含某个字符,在本例中为“#”,并且在该字符“#”的其他外观中,只删除该字符,而不是这个词。

所以字符串:

  

#great day #happy

会变成:

  

多么美好的一天

到目前为止我已经尝试了

    entry = re.sub('(?<=#)\w+','',entry) 

但这会删除包含'#'的所有单词。

2 个答案:

答案 0 :(得分:1)

import re

print(re.sub(r'''(?x)    # VERBOSE mode
                 [#]     # literal #
                 |       # or
                 \s*     # zero-or-more spaces
                 \w*     # zero-or-more alphanumeric characters 
                 [#]     # literal #
                 \w*     # zero-or-more alphanumeric characters 
                 $       # end of line
                 ''',
             '', # substitute matched text with an empty string
             'What a #great day #happy'))

产量

What a great day

答案 1 :(得分:0)

import re

s='What a #great day #happy'

# Test if the last word has a '#'
if re.match('#',s.rsplit(' ', 1)[1]):
    # Deal with everything but last word and do replacement         
    print re.sub('#', '',s.rsplit(' ', 1)[0])  
else:
    # Else replace all '#' 
    print re.sub('#', '',s) 

>>> What a great day