示例#1
0
 /// <summary>
 /// Returns a copy of the given string with text replaced using a regular expression.
 /// </summary>
 /// <param name="input"> The string on which to perform the search. </param>
 /// <param name="replaceFunction"> A function that is called to produce the text to replace
 /// for every successful match. </param>
 /// <returns> A copy of the given string with text replaced using a regular expression. </returns>
 internal string Replace(string input, FunctionInstance replaceFunction)
 {
     return(this.value.Replace(input, match =>
     {
         object[] parameters = new object[match.Groups.Count + 2];
         for (int i = 0; i < match.Groups.Count; i++)
         {
             if (match.Groups[i].Success == false)
             {
                 parameters[i] = Undefined.Value;
             }
             else
             {
                 parameters[i] = match.Groups[i].Value;
             }
         }
         parameters[match.Groups.Count] = match.Index;
         parameters[match.Groups.Count + 1] = input;
         return TypeConverter.ToString(replaceFunction.CallLateBound(null, parameters));
     }, this.Global == true ? int.MaxValue : 1));
 }
示例#2
0
        /// <summary>
        /// Returns a copy of this string with text replaced using a replacement function.
        /// </summary>
        /// <param name="thisObj"> The string that is being operated on. </param>
        /// <param name="substr"> The text to search for. </param>
        /// <param name="replaceFunction"> A function that is called to produce the text to replace
        /// for every successful match. </param>
        /// <returns> A copy of this string with text replaced. </returns>
        internal static string Replace(string thisObj, string substr, FunctionInstance replaceFunction)
        {
            // Find the first occurrance of substr.
            int start = thisObj.IndexOf(substr, StringComparison.Ordinal);

            if (start == -1)
            {
                return(thisObj);
            }
            int end = start + substr.Length;

            // Get the replacement text from the provided function.
            var replaceText = TypeConverter.ToString(replaceFunction.CallLateBound(null, substr, start, thisObj));

            // Replace only the first match.
            var result = new System.Text.StringBuilder(thisObj.Length + (replaceText.Length - substr.Length));

            result.Append(thisObj, 0, start);
            result.Append(replaceText);
            result.Append(thisObj, end, thisObj.Length - end);
            return(result.ToString());
        }