[Webinar] Streamline your web hosting managementRegister Today

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 298
  • Last Modified:

Converting VBScript FormatString function to C# function

Hi Experts,

I am having below function code in VbScript, now I want to write same function in C# 2.0 code.
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))
	Set matches = nothing
	Set RegExp = nothing

	FormatString = result
End Function

Open in new window

Please suggest!!
1 Solution
Om PrakashCommented:
Regex are supported by C#. pl check the following link for examples. you can put above pattern it will work.

käµfm³d 👽Commented:
Try this:
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;

Open in new window

The regular expression you are trying to match looks like the built in .NET String.Format method formatting.
If you have the string "This {0} a {1} for the {1} {2}" and you gave it an array of string values "is", "test", and "team" you want the end result to be "This is a test for the test team". Is this correct? If this is the case you don't need to create a separate method. There are several methods that do formatting like this in .NET (String.Format, Console.WriteLine, etc). If this the formatting you are looking for here's a link for more info on the method:

And .NET string formatting:

string format = "This {0} a {1} for the {1} {2}";
string[] values = string[3] {"is", "test", "team"};
string returnValue = String.Format(format, values);

Open in new window

You can also just list the values in the parameters without the array with the same result:

string format = "This {0} a {1} for the {1} {2}";
string returnValue = String.Format(format, "is", "test", "team");

Open in new window


Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now