Regex to remove hashtags but to keep first hashtag

257 Views Asked by At

I want to remove all hashtags from a text but it should keep the first hashtag

Example text:

This is an example #DoNotRemoveThis #removethis #removethis #removethis

Expected result:

This is an example #DoNotRemoveThis

I'm using this

\#\w+\s? 

but it remove all the hashtags. I want to keep the first hashtag

2

There are 2 best solutions below

0
BM- On

This may require further knowledge as to what flavour of regex you are using. For example, if .NET (C#) you can do variable length look-behind, and thus the following pattern will do what you need:

(?<=#.*)(#\w+)/g

Test at Regex101

However, this won't work in most other engines.

0
Andy Lester On

It sounds to me like you want to match everything up to but not including the second hash symbol, right?

/^[^#]*#[^#]*/

That will match any number of non-hash characters, then a hash character, then more non-hash characters.