How to remove words with # or $ at the end of a sentence to be removed (Regex)

Viewed 83

I have the following:

The moment #BTC, we have all $BTC been waiting for:We are happy to announce NIX Platform is rebranding to.. $NBT > $VOICE $NIX > $MUTE $ETH $BTC #BTC

I would like to remove only the remove the words with # or $ to be removed from the end, not the middle, so the above string would look like this

The moment #BTC, we have all $BTC been waiting for:We are happy to announce NIX Platform is rebranding to..  >  > 

Currently I have #(?!(?:hashtag)\b)[\w-]+(?=(?:\s+#[\w-]+)*\s*$) as regex that removes words with # from end but not $, not sure what I need to include those as well

2 Answers

An alternative regex with a word boundary and negative lookahead to disallow any word character following a whitespace:

[#$@]\w+\b(?!\W*\s\w)

RegEx Demo

RegEx Explanation:

  • [#$@]: Match # or $ or @
  • \w+b: Match 1+ word characters followed by word boundary
  • (?!\W*\s\w): Negative lookahead to assert that we don't have a word character after a whitespace ahead of current position

Alternatively, you can also use an *atomic group` to disallow backtracking:

[#$@](?>\w+)(?!\W*\s\w)

You could use a positive lookahead and assert that until the end of the string all words start with a non word character.

[#$][^\s$#]+(?=(?:\s+[^\w\s]\S*)*\s*$)
  • [#$][^\s$#]+ Match either # or $ and 1+ occurrences of any char except # or $
  • (?= Positive lookahead, assert on the right
    • (?:\s+[^\w\s]\S*)* Optional repetitions of 1 or more whitespace chars followed by any char except a whitspace or char char
    • \s* Match optional trailing whitspace chars
    • $ End of string
  • ) Close lookahead

Regex demo


If the start with $ or # can contain the other one, another option could be using a tempered greedy token approach with a capture group and a backreference \1.

To prevent partial matches, you might add asserting a whitespace boundary at the left.

(?<!\S)([#$])(?:(?!\1)\S)*(?=(?:\s+[^\w\s]\S*)*\s*$)

Regex demo

Related