locked
function to return regex matches RRS feed

  • Question

  • User-352524747 posted
    @functions {
        public static string HashTags(string hts)
        {
            MatchCollection matchtgs = Regex.Matches(hts, @"\B#\w\w+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            foreach (Match ht in matchtgs)
            {
                hts = ht.Value;
            }
            return hts;
        }
    }
    @foreach (var keyword in CFunction.HashTags(item.Content))
                                {
                                <p>keyword</p>
                                }

    I'm not finding the proper way to make this work. I want to match all the hashtags in a string using a function.

    Tuesday, February 21, 2017 1:05 PM

Answers

  • User281315223 posted

    If you want to grab all of them, consider returning a collection instead of a string :

    public static List<string> HashTags(string hts)
    {
    	var hashtags = new List<string>();
            MatchCollection matchtgs = Regex.Matches(hts, @"\B#\w\w+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            foreach (Match ht in matchtgs)
            {
                hashtags.Add(ht.Value);
            }
       	return hashtags;
    }

    This will allow you to iterate through them as expected. You can see a very basic example of this here.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, February 21, 2017 2:14 PM