简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM