// C++ Code
#include "stdafx.h"
using namespace System;
using namespace System::Text::RegularExpressions;
int main(array<System::String ^> ^args)
{
Regex^ rx = gcnew Regex(L"^-?\\d+(\\.\\d{2})?{1}quot;);
array<String^>^tests = {L"-42", L"19.99", L"0.001", L"100 USD"};
System::Collections::IEnumerator^ myEnum = tests->GetEnumerator();
while (myEnum->MoveNext())
{
String^ test = safe_cast<String^>(myEnum->Current);
if (rx->IsMatch(test))
{
Console::WriteLine(L"{0} is a currency value.", test);
}
else
{
Console::WriteLine("{0} is not a currency value.", test);
}
}
Console::ReadLine();
return 0;
}
// C# Code
using System;
using System.Text.RegularExpressions;
namespace exp
{
public class Program
{
public static void Main()
{
Regex rx = new Regex("^-?\\d+(\\.\\d{2})?{1}quot;);
String[] tests = {"-42", "19.99", "0.001", "100 USD"};
System.Collections.IEnumerator myEnum = tests.GetEnumerator();
while (myEnum.MoveNext())
{
String test = (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);
}
}
Console.ReadLine();
}
}
}
以上代码输出结果都是:
-42 is a currency value.
19.99 is a currency value.
0.001 is not a currency value.
100 USD is not a currency value.
C# 语言的 foreach 语句(在 C++ 中为 for each,在 Visual Basic 中为 For Each)隐藏了枚举数的复杂性。 因此,建议使用 foreach,而不直接操作枚举数。故以上代码可以改写成for each 和 foreach 语句实现:
// C++ Code
#include "stdafx.h"
using namespace System;
using namespace System::Text::RegularExpressions;
int main(array<System::String ^> ^args)
{
Regex^ rx = gcnew Regex(L"^-?\\d+(\\.\\d{2})?{1}quot;);
array<String^>^tests = {L"-42", L"19.99", L"0.001", L"100 USD"};
for each (String^ test in tests)
{
if (rx->IsMatch(test))
{
Console::WriteLine(L"{0} is a currency value.", test);
}
else
{
Console::WriteLine("{0} is not a currency value.", test);
}
}
Console::ReadLine();
return 0;
}
// C# Code
using System;
using System.Text.RegularExpressions;
namespace exp
{
public class Program
{
public static void Main()
{
Regex rx = new Regex("^-?\\d+(\\.\\d{2})?{1}quot;);
String[] tests = {"-42", "19.99", "0.001", "100 USD"};
System.Collections.IEnumerator myEnum = tests.GetEnumerator();
foreach (String test in tests)
{
if (rx.IsMatch(test))
{
Console.WriteLine("{0} is a currency value.", test);
}
else
{
Console.WriteLine("{0} is not a currency value.", test);
}
}
Console.ReadLine();
}
}
}
参考:
[1]http://msdn.microsoft.com/zh-cn/library/system.array.getenumerator.aspx#Y831