Sunday 21 December 2008

Get-RegexTest.ps1

  1. # Get-RegexTest.ps1 
  2. # Sample Using PowerShell 
  3. # Thomas Lee - tfl@psp.co.uk 
  4.  
  5. # Define a regular expression for currency values. 
  6. $rx = New-Object system.text.RegularExpressions.Regex "^-?\d+(\.\d{2})?$" 
  7.  
  8. # Define tests 
  9. $tests = "-42", "19.99", "0.001", "100 USD", ".34", "0.34", "1,052.21", "Jerry Garcia" 
  10.  
  11. # Now test and report 
  12. foreach ($test in $tests)  { 
  13. if ($rx.IsMatch($test)) { 
  14. "{0} is a currency value." -f $test 
  15. else
  16. "{0} is not a currency value." -f $test 
  17. }     

This script produces the following output:

PS C:\foo> .\GetRegexTest.ps1'
-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.
.34 is not a currency value.
0.34 is a currency value.
1,052.21 is not a currency value.
Jerry Garcia is not a currency value.

No comments: