Link to home
Start Free TrialLog in
Avatar of tia_kamakshi
tia_kamakshiFlag for United Arab Emirates

asked on

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))
	Next
	Set matches = nothing
	Set RegExp = nothing

	FormatString = result
End Function

Open in new window


Please suggest!!
Avatar of Om Prakash
Om Prakash
Flag of India image

Regex are supported by C#. pl check the following link for examples. you can put above pattern it will work.

http://www.dotnetperls.com/regex-replace
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DSmithVz
DSmithVz

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:
http://msdn.microsoft.com/en-us/library/system.string.format.aspx

And .NET string formatting:
http://msdn.microsoft.com/en-us/library/txafckwd.aspx

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