Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find hashtags in string

Tags:

c#

xamarin

I am working on a Xamarin.Forms PCL project in C# and would like to detect all the hashtags.

I tried splitting at spaces and checking if the word begins with an # but the problem is if the post contains two spaces like "Hello #World Test" it would lose that the double space

string body = "Example string with a #hashtag in it";
        string newbody = "";
        foreach (var word in body.Split(' '))
        {
            if (word.StartsWith("#"))
                newbody += "[" + word + "]";
            newbody += word;
        }

Goal output:

Example string with a [#hashtag] in it

I also only want it to have A-Z a-z 0-9 and _ stopping at any other character

Test #H3ll0_W0rld$%Test => Test [#H3ll0_W0rld]$%Test

Other Stack questions try to detect the string and extract it, I would like it work with it and put it back in the string without losing anything that methods such as splitting by certain characters would lose.

like image 939
Dan Avatar asked Oct 21 '25 12:10

Dan


1 Answers

You can use Regex with #\w+ and $&

Explanation

  • # matches the character # literally (case sensitive)
  • \w+ matches any word character (equal to [a-zA-Z0-9_])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

$& Includes a copy of the entire match in the replacement string.

Example

var input = "asdads sdfdsf #burgers, #rabbits dsfsdfds #sdf #dfgdfg";
var regex = new Regex(@"#\w+");
var matches = regex.Matches(input);
foreach (var match in matches)
{
    Console.WriteLine(match);
}

or

var result = regex.Replace(input, "[$&]" );
Console.WriteLine(result);

Ouput

#burgers
#rabbits
#sdf
#dfgdfg
asdads sdfdsf [#burgers], [#rabbits] dsfsdfds [#sdf] [#dfgdfg]

Updated Demo here

Another Example

like image 153
TheGeneral Avatar answered Oct 23 '25 01:10

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!