Thursday, July 10, 2008

C# version of VB6/VBA's Val function

Here is some code to emulate VB6/VBA's Val function in C#. I found the original http://www.dreamincode.net/code/snippet1821.htm but it needed some changes to work correctly.


using System.Text.RegularExpressions;

using System;



namespace ValinCS

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine(Val("AAA234"));

Console.WriteLine(Val("1234asdv"));

Console.WriteLine(Val(" 345"));

Console.WriteLine(Val("1.2345f"));

Console.WriteLine(Val(" 1 2"));

Console.WriteLine(Val(""));

Console.WriteLine(Val("12"));

}



private static int Val(string value)

{

string returnVal = string.Empty;

int tryInt = 0;

//^ specifies that the match has to start at the start of the string

//Trim() trims both ends of the string before matching

MatchCollection collection = Regex.Matches(value.Trim(), "^\\d+");

foreach (Match match in collection)

{

returnVal += match.ToString();

}



//attempt conversion to int

int.TryParse(returnVal,out tryInt);

return tryInt;

}

}

}



0 Comments:

Post a Comment

<< Home