我需要一个 Python 中的正则表达式,如果它包含某个字符,则从字符串中删除最后一个单词,在本例中为“#”,而在该字符“#”的其他出现中,仅删除该字符,而不是这个词。
所以字符串:
What a #great day #happy
会变成:
What a great day
到目前为止我已经尝试过了
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
