My goal is to check if a string contains any string values from a list, store that value and wrap it in HTML-tags. I’m kind of lost here.
My List:
public List<string> AccessModifiers
{
get { return _accessModifiers ?? (_accessModifiers = new List<string>()); }
}
With the values addes in a separate method:
AccessModifiers.Add("public");
AccessModifiers.Add("private");
AccessModifiers.Add("protected");
AccessModifiers.Add("internal");
AccessModifiers.Add("protected internal");
AccessModifiers.Add("void");
Let’s say i was sendind the text protected void TagListView_ItemDataBound(object sender, ListViewItemEventArgs e) to the code below, what I want is to get the keywords protected and void as matchedItems to wrap in my HTML-tags. It feels like the Find method should check if the item is found, not the whole list, but I’m a bit lost here. Here’s what I got so far:
foreach (var item in AccessModifiers)
{
if (UsedItems == null) // If the session is null...
{
UsedItems = new List<string>(); // ...a new one is initiated
}
if(!UsedItems.Contains(item)) // Check if the iterated item is found in the session-list
{
bool match = AccessModifiers.Any(ArticleTextBox.Text.Contains);
string matchedItem = AccessModifiers.Find(ArticleTextBox.Text.Contains);
if (match == true)
{
string openTag = "<span class='accessModifiers'>";
string closeTag = "</span>";
string newModifier = openTag + matchedItem + closeTag;
newText = newText.Replace(matchedItem, newModifier);
UsedItems.Add(matchedItem); // Add the matchedItem (used item) to the session-list not to be iterated again
}
}
}
return newText;
I can at this point only get the keyword protected to be stored, not void. It seems like it would be more simple than what I’ve come up with so far.
Quite the reverse. In particular, while the example you’ve given is simple, the general case isn’t:
Basically you’ll need code which understands the structure of code rather better. Simple search and replace isn’t going to cut it.
The code highlighter I use on csharpindepth.com is based on a VB highlighter written by Jared Parsons. I’ll see whether I can find the original source – but if not, I’m sure there are other open source code highlighters available.
EDIT: If you really are happy with just doing a naive search and replace, then you’re definitely making it more complicated than you need to.
Then you’ve just got: