Skip to content Skip to sidebar Skip to footer

Regex To Remove The Last Word If It Contains A Character

I need a regex in Python that will remove the last word from a string if it contains a certain character, in this case '#', and in other appearances of that character '#', only the

Solution 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'))

yields

What a great day

Solution 2:

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

Post a Comment for "Regex To Remove The Last Word If It Contains A Character"