I have a collection of strings such as Some song [FEAT. John Doe] and I'm trying to extract the 'featured' part. It could be identified by one of several different words "FEAT|FEAT\\.|Featuring" and may or may not be enclosed by brackets. I'm using a Regex for this and here is what I've got so far:
[TestMethod]
public void ExtractFeaturedPerformers()
{
IEnumerable<string> titles = new string[]
{
"abc [FEAT one two] 123",
"def(FEAT. three'four) 456",
"ghi Featuring five",
"jkl"
};
// Must be able to use an arbitrary array of words
var arrayOfWords = new string[] { "FEAT", "FEAT.", "Featuring" };
string options = string.Join("|", arrayOfWords.Select(s => Regex.Escape(s)));
var result = new List<string>();
foreach(string title in titles)
{
var _ = Regex.Match(title, $@"(?<=({options})\s*)(.*?)(?=[\]\)]|$)");
if (_.Success)
result.Add(_.Value);
}
Assert.AreEqual(3, result.Count());
Assert.IsTrue(result.Contains("one two"));
Assert.IsTrue(result.Contains("three'four"));
Assert.IsTrue(result.Contains("five"));
}
I have it mostly working but there are two limitations. My main problem is that the second result includes the ..
. three'four
How can I remove this as part of the Regex so that I can accept an arbitrary options string rather than stripping it away later? Dealing with the . is my main concern but I would also appreciate suggestions for removing the leading and trailing whitespace from the result so that I don't have to call Trim() later.