现在的位置: 首页 > 综合 > 正文

Regex 101 Exercise I8 – replace space count with spaces

2013年06月27日 ⁄ 综合 ⁄ 共 1454字 ⁄ 字号 评论关闭
    In this episode, Eric asks us to replace space count with spaces:
--------------------------------------------------------------------------------

Given a string with embedded space counts:

<15sp>Indented by 15 spaces

Replace the <<count>sp> with <count> spaces.

So, if you have

<4sp>Text

you should end up with

    Text

----------------------------------------------------------------------------------

and my answer is:


using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

/*Regex 101 Exercise I8 - replace space count with spaces*/
namespace RegexExerciseI8
{
    
class Program
    {

        static void Main(String[] args)
        {
            Regex regex 
= new Regex(@"<(\d+)sp>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Console.WriteLine(
"Type in the text you want to process:");
            String inputHtml 
= Console.ReadLine();
            String resultHtml 
= regex.Replace(inputHtml, delegate(Match match)
            {
                
return new String(' ', Int32.Parse(match.Groups[1].Value));
            });

            Console.WriteLine(resultHtml);
        }
    }
}


    I think this exercise is very interesting and helpful, imagine that you are currently working on a text processing application, and you want the text to be formatted in a given way, i.e indentation, justfication, left alignment or right alignment etc, and you can add some formatting tags in the raw text, and use regular expression to match the individual formatting tags, and replace them with the predefined formats.
    The possibility is endless.

抱歉!评论已关闭.