nemak ner
nemak ner

Reputation: 19

Regex to remove hashtags but to keep first hashtag

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

Upvotes: 1

Views: 304

Answers (2)

Andy Lester
Andy Lester

Reputation: 93805

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.

Upvotes: 0

BM-
BM-

Reputation: 626

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.

Upvotes: 0

Related Questions