这个VBScript函数在做什么?

本文关键字:什么 VBScript 函数 这个 | 更新日期: 2023-09-27 18:12:41

我在VBScript中有一个函数,它在做什么?如何使用c# 2.0来简化它

Function FormatString(format, args)
    Dim RegExp, result
    result = format
    Set RegExp = New RegExp 
    With RegExp
        .Pattern = "'{('d{1,2})'}"
        .IgnoreCase = False
        .Global = True
    End With
    Set matches = RegExp.Execute(result)
    For Each match In matches   
        dim index
        index = CInt(Mid(match.Value, 2, Len(match.Value) - 2))
        result = Replace(result, match.Value, args(index))
    Next
    Set matches = nothing
    Set RegExp = nothing
    FormatString = result
End Function

谢谢!

这个VBScript函数在做什么?

看起来像是。net字符串的简化版本。格式方法。

它接受一个带有花括号分隔的占位符的格式字符串(例如"{0} {1}"),并用args数组中的对应值依次替换每个占位符。您可以将其替换为String.Format,而不会改变其功能。

它在一个字符串中搜索与指定的regex模式匹配的所有内容,并将其替换为传递给函数的列表中的其他字符串。

基于我的(有限的)技能与regex,它似乎在寻找输入字符串中的1或2位数的数字,并将它们替换为传递给函数的数组中的值。

这是来自MSDN的一些文档。http://msdn.microsoft.com/en-us/library/hs600312.aspx

可以用String代替。格式如下http://msdn.microsoft.com/en-us/library/system.string.format.aspx

和链接页面中的用法示例。

DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0); 
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
                              dat, city, temp);
Console.WriteLine(output);
// The example displays the following output:
//    At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.   

我将代码转换为c#

static string FormatString(string format, string[] args)
{
    System.Text.RegularExpressions.Regex RegExp;
    System.Text.RegularExpressions.MatchCollection matches;
    string result;
    result = format;
    RegExp = new System.Text.RegularExpressions.Regex(@"'{('d{1,2})'}", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
    matches = RegExp.Matches(result);
    foreach (System.Text.RegularExpressions.Match match in matches)
    {
        int index;
        index = Convert.ToInt32(match.Value.Substring(1, match.Value.Length - 1));
        result = result.Replace(match.Value, args[index]);
    }
    matches = null;
    RegExp = null;
    return result;
}

有任何问题请告诉我