Mittwoch, 28. November 2007

BATCH_ Test a String for Number

Testing a String for a number that can only contain the ciphers 0 to 9 and optionally a prefixed - character can be done with the following subroutine.
:: Checks if the first parameter is a number, that is it only contains the
:: characters 0 to 9 and additionally the minus as the first character.
:: PARAM
:: 1 string to test for number
:: RETURN String "true" if string is a valid number, "false" otherwise
:IS_NUMBER
SETLOCAL
FOR /F "tokens=*" %%A IN ('SET /A %~1 2^>^&1') DO (
    IF "%~1" == "%%A" (
       SET RESULT=true
    ) ELSE (
       SET RESULT=false
    )
)
ENDLOCAL & SET RESULT=%RESULT%
GOTO :EOF
This tests the input string using the SET /A arithmetic extension.
However this test two limits I can think of:
  • As SET /A echoes the error Missing operand. on invalid input, a test against that very string will return true.
  • A number with leading zeros like 007 will not be recognized as a number.
If you cannot live with these limitations, you have to replace this relatively fast solution with two loops doing something like this:
FOR EACH CHARACTER (
    FOR %%A IN (0-9) (
        IF (%%A == CHAR) (
            GOTO :END_INNER
        )
    )
    GOTO:EOF & FAIL
    :END_INNER
)

Reflog

Informationstechnische Howtos, Hinweise und Merkwürdiges

Batchlib v1.0 2008-03-29

Aktuelle Beiträge

HOWTO_ O2 DSL Surf &...
Der O2 DSL Surf & Phone-Router ist für die...
cypressor - 12. Feb, 19:57
Uptweak Windows XP Home...
There are a lot of annoying limitations in Windows...
cypressor - 9. Okt, 19:30
BATCHLIB_ Batchlib package...
Download Batchlib package v1.0 (5 KB zip file) What...
cypressor - 29. Mrz, 19:10
BATCHLIB_ Batchlib library...
The batchlib library string.cmd is part of the batchlib...
cypressor - 29. Mrz, 18:10

Homepage Ticker

Links

Status

Online seit 4202 Tagen
Zuletzt aktualisiert: 28. Jun, 11:32
RSS XML 1.0 Button-Get-Firefox

batch
batchlib
howto
tech
video
Profil
Abmelden
Weblog abonnieren