Mega Code Archive

 
Categories / C# / Regular Expressions
 

Replace string with regular expression

// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Utils.cs" company="Collaboris Ltd."> //   Copyright (c) Collaboris Ltd. All rights Reserved. // </copyright> // <summary> //   The utils. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Collaboris.DataAccess {     #region Imports     using System;     using System.Web;     #endregion     /// <summary>     /// The utils.     /// </summary>     public class Utils     {         #region [rgn] Methods (2)         /// <summary>         /// The replace ex.         /// </summary>         /// <param name="original">         /// The original.         /// </param>         /// <param name="pattern">         /// The pattern.         /// </param>         /// <param name="replacement">         /// The replacement.         /// </param>         /// <returns>         /// The replace ex.         /// </returns>         public static string ReplaceEx(string original, string pattern, string replacement)         {             int count, position0, position1;             count = position0 = position1 = 0;             string upperString = original.ToUpper();             string upperPattern = pattern.ToUpper();             int inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);             var chars = new char[original.Length + Math.Max(0, inc)];             while ((position1 = upperString.IndexOf(upperPattern, position0)) != -1)             {                 for (int i = position0; i < position1; ++i)                 {                     chars[count++] = original[i];                 }                 for (int i = 0; i < replacement.Length; ++i)                 {                     chars[count++] = replacement[i];                 }                 position0 = position1 + pattern.Length;             }             if (position0 == 0)             {                 return original;             }             for (int i = position0; i < original.Length; ++i)             {                 chars[count++] = original[i];             }             return new string(chars, 0, count);         }                 #endregion [rgn]     } }