I have a text editor similar to what is used on stack overflow. I am processing the text string in c# but also allowing users to format text within that using a custom tag. For example..
<year /> will output the current year.
"Hello <year /> World" would render Hello 2012 World
What I would like to do is to create a regular expression to search the string for any occurance of <year /> and replace it. Further to that, I would also like to add attributes to the tag and be able to extract them so <year offset="2" format="5" />. I’m not great with RegEx but hopefully someone out there knows how to do this?
Thanks
Ideally you shouldn’t be using regex for this; but seeing as Html Agility Pack doesn’t have a
HtmlReaderI guess you have to.That being said, looking at other markup solutions, they often use a list of regex patterns and the relevant replacement – so we shouldn’t write a ‘general’ case (e.g.
<([A-Z][A-Z0-9]*)>.*?</\1>would be the wrong thing to do here, instead we would want<year>.*?</year>).Initially you would probably create a class to hold information about a recognised token, for example:
Now we need to create the regex. For example, a regex to match your
yearelement would look like:So we can generalise this to:
Given those general tag regexes we can write the markup class:
It’s all really rough work, but it should give you a good idea of what you should be doing.