diff --git a/mentionnutil/extractor.go b/mentionnutil/extractor.go new file mode 100644 index 0000000..a9140f2 --- /dev/null +++ b/mentionnutil/extractor.go @@ -0,0 +1,30 @@ +package mentionnutil + +import ( + "regexp" + "strings" + + "github.com/upfluence/pkg/slices" + "github.com/upfluence/pkg/stringutil" +) + +var mentionRegex = regexp.MustCompile(`\B@[\w\.]+[\w]+`) + +func ExtractMentions(s string) []string { + mentions := slices.Map( + mentionRegex.FindAllString(s, -1), + func(v string) string { + return strings.TrimPrefix(v, "@") + }, + ) + + if len(mentions) == 0 { + return nil + } + + var set stringutil.Set + + set.Add(mentions...) + + return set.Strings() +} diff --git a/mentionnutil/extractor_test.go b/mentionnutil/extractor_test.go new file mode 100644 index 0000000..130eadd --- /dev/null +++ b/mentionnutil/extractor_test.go @@ -0,0 +1,37 @@ +package mentionnutil + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestExtractMentions(t *testing.T) { + for _, tt := range []struct { + name string + input string + expect []string + }{ + { + name: "empty", + }, + { + name: "no mentions", + input: "foo bar", + }, + { + name: "multi mentions", + input: "foo bar @buz. @taz_ @dot.name hello @buz @with_1", + expect: []string{"buz", "taz_", "dot.name", "with_1"}, + }, + { + name: "youtube url", + input: "foo bar @buz. https://www.youtube.com/@SalonViking test", + expect: []string{"buz", "SalonViking"}, + }, + } { + t.Run(tt.name, func(t *testing.T) { + assert.ElementsMatch(t, tt.expect, ExtractMentions(tt.input)) + }) + } +}