2011-10-28 131 views
1

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

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 

谢谢!

+0

看起来像VB.NET对我来说,不是的VBScript - 非常不同的动物。 – Tim

回答

1

我转换的代码转换为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; 
} 

请让我知道的任何问题

4

看起来像.NET String.Format方法的简化版本。

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

+0

你可以请一些代码示例建议!谢谢 –

+0

这与string.format无关。它使用正则表达式模式匹配。 –

+3

@BradleyUffner它使用正则表达式模式匹配来实现一个非常简化版本的string.format – Jon

1

它正在搜索匹配指定正则表达式模式的所有字符串,并将其替换为传入该函数的列表中的其他字符串。

基于我的(有限)正则表达式的技能,它似乎在输入字符串中寻找1或2位数字,并将其替换为传入该函数的数组中的值。

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

它可以用的​​String.Format来代替,这里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.