Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6611571
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T19:59:13+00:00 2026-05-25T19:59:13+00:00

I have a text editor similar to what is used on stack overflow. I

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T19:59:13+00:00Added an answer on May 25, 2026 at 7:59 pm

    Ideally you shouldn’t be using regex for this; but seeing as Html Agility Pack doesn’t have a HtmlReader I 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:

    public class Token
    {
        private Dictionary<string, string> _attributes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        public string InnerText { get; private set; }
    
        public string this[string attributeName]
        {
            get
            {
                string val;
                _attributes.TryGetValue(attributeName, out val);
                return val;
            }
        }
    
        public Token(string innerText, IEnumerable<KeyValuePair<string, string>> values)
        {
            InnerText = innerText;
            foreach (var item in values)
            {
                _attributes.Add(item.Key, item.Value);
            }
        }
    
        public int GetInteger(string name, int defaultValue)
        {
            string val;
            int result;
            if (_attributes.TryGetValue(name, out val) && int.TryParse(val, out result))
                return result;
            return defaultValue;
        }
    }
    

    Now we need to create the regex. For example, a regex to match your year element would look like:

    <Year(?>\s*(?<aname>\w*?)\s*=\s*"(?<aval>[^"]*)"\s*)*>(?<itext>.*?)</Year>
    

    So we can generalise this to:

    <{0}\s*(?>(?<aname>\w*?)\s*=\s*"(?<aval>[^"]*)"\s*)*>(?<itext>.*?)</{0}>
    <{0}\s*(?>(?<aname>\w*?)\s*=\s*"(?<aval>[^"]*)"\s*)*/>
    

    Given those general tag regexes we can write the markup class:

    public class MyMarkup
    {
        // These are used to build up the regex.
        const string RegexInnerText = @"<{0}\s*(?>(?<aname>\w*?)\s*=\s*""(?<aval>[^""]*)""\s*)*>(?<itext>.*?)</{0}>";
        const string RegexNoInnerText = @"<{0}\s*(?>(?<aname>\w*?)\s*=\s*""(?<aval>[^""]*)""\s*)*/>";
    
        private static LinkedList<Tuple<Regex, MatchEvaluator>> _replacers = new LinkedList<Tuple<Regex, MatchEvaluator>>();
    
        static MyMarkup()
        {
            Register("year", false, tok =>
            {
                var count = tok.GetInteger("digits", 4);
                var yr = DateTime.Now.Year.ToString();
                if (yr.Length > count)
                    yr = yr.Substring(yr.Length - count);
                return yr;
            });
        }
    
        private static void Register(string tagName, bool supportsInnerText, Func<Token, string> replacement)
        {
            var eval = CreateEvaluator(replacement);
    
            // Add the no inner text variant.
            _replacers.AddLast(Tuple.Create(CreateRegex(tagName, RegexNoInnerText), eval));
            // Add the inner text variant.
            if (supportsInnerText)
                _replacers.AddLast(Tuple.Create(CreateRegex(tagName, RegexInnerText), eval));
        }
    
        private static Regex CreateRegex(string tagName, string format)
        {
            return new Regex(string.Format(format, Regex.Escape(tagName)), RegexOptions.Compiled | RegexOptions.IgnoreCase);
        }
    
        public static string Execute(string input)
        {
            foreach (var replacer in _replacers)
                input = replacer.Item1.Replace(input, replacer.Item2);
            return input;
        }
    
        private static MatchEvaluator CreateEvaluator(Func<Token, string> replacement)
        {
            return match =>
            {
                // Grab the groups/values.
                var aname = match.Groups["aname"];
                var aval = match.Groups["aval"];
                var itext = match.Groups["itext"].Value;
    
                // Turn aname and aval into a KeyValuePair.
                var attrs = Enumerable.Range(0, aname.Captures.Count)
                    .Select(i => new KeyValuePair<string, string>(aname.Captures[i].Value, aval.Captures[i].Value));
    
                return replacement(new Token(itext, attrs));
            };
        }
    }
    

    It’s all really rough work, but it should give you a good idea of what you should be doing.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hi I have text editor widget in smalltalk (visual works) that returns a text
I have a text editor like program which is a QMainWindow inherited class. There,
I have a huge text file (~1GB) and sadly the text editor I use
I have written an advanced text editor component (fixed-width, syntax highlighting, etc.) in Delphi,
I have recently started using Vim as my text editor and am currently working
I have a problem with the FreeTextBox rich Text Editor in my ASP.NET site.
If I have the following text in my Eclipse editor: Text Line 1 Text
I have a seesaw ui with a text editor. The editor content is backed
I am making text editor in netbeans and have added jMenuItems called Copy,Cut &
I have a an HTML form which contains the YAHOO rich text editor on

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.