Volunteer .NET Evangelist

A well oiled machine can’t run efficiently, if you grease it with water.
  首页  :: 联系 :: 订阅 订阅  :: 管理

Regex 101 Exercise I8 - replace space count with spaces

Posted on 2006-02-15 20:03  Sheva  阅读(1470)  评论(0编辑  收藏  举报
    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.