Saturday, January 9, 2010

Regex check Currency value

The following code example illustrates the use of a regular expression to check whether a string has the correct format to represent a currency value. Note the use of enclosing ^ and $ tokens to indicate that the entire string, not just a substring, must match the regular expression.


#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{

// Define a regular expression for currency values.
Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" );

// Define some test strings.
array<String^>^tests = {"-42","19.99","0.001","100 USD"};

// Check each test string against the regular expression.
System::Collections::IEnumerator^ myEnum = tests->GetEnumerator();
while ( myEnum->MoveNext() )
{
String^ test = safe_cast<String^>(myEnum->Current);
if ( rx->IsMatch( test ) )
{
Console::WriteLine( "{0} is a currency value.", test );
}
else
{
Console::WriteLine( "{0} is not a currency value.", test );
}
}
}

No comments:

Post a Comment

 
Blogverzeichnis - Blog Verzeichnis bloggerei.de Blog Suche