特定の文字、この場合は「#」が含まれている場合、文字列から最後の単語を削除する Python の正規表現が必要です。その文字「#」の他の外観では、単語ではなく文字のみが削除されます。
したがって、文字列:
なんて #素晴らしい日 #幸せ
次のようになります。
なんて良い日だ
これまで私は試しました
entry = re.sub('(?<=#)\w+','',entry)
ただし、これにより「#」を含むすべての単語が削除されます。
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
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