Home > Blockchain >  Regex to remove hashtags but to keep first hashtag
Regex to remove hashtags but to keep first hashtag

Time:12-05

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related