John Boe
John Boe

Reputation: 3611

How to detect number in string in CMD

I try to parse file and the need to detect number for every column in the tags. I need to detect:

  1. If there is a number
  2. If the number is 1-3 digits.
  3. If there is a single dot at the begin, end or a separated dot (I can do the last two detections of dot with string substitution but detection of number I don't know).

I already have the for loop that extracts the data in tags:

for %%Z in (hide_2.htm) do (
    for /F "tokens=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 delims=<>" %%A on ('grep -B 1411 -E "</table>" %%Z ^| grep -E ^"^(display^|^^\d\d{1,3}^|country^|^<td^>HTTP^|rightborder^).*$^" ') do (
        echo A:%%A + %%B + %%C + %%D + %%E + %%F + %%G + %%H + %%I + %%J + %%K + %%L
        pause
    )
)

The input is: A: + td + span + span + 41 + /span + span style="display: none;" + 111 + /span + div + +
A: style="display: none;" + 190 + /div + span class="" style="" +. + /span + span + 197 + /span + span + +
A: style="display: none;" + 24 + /span + span + /span + . + span style="display: + + + + +
A:inline;" + 132 + /span + span style="display: none;" + 39 + /span + . + span + + + +
A:style="display: inline;" + 186 + /span + /span + /td + + + + + + +
A: + td rel="rw" + span class="country" + img + + + + + + + +
A: + td + HTTPS + /td + + + + + + + +

The source data are taken from here.

Edit: The best would be to keep two variables. 1st variable to keep the number, and the second variable to keep the dot or a flag if the dot exists.

Edit2: The input values can be for example: 120,132,186,24,111,41,., or .120,.132,.186,.24,.111,.41 ... The values can be in any of the columns.

Edit3: The number is always on the end of column. And the dot can be on begin but must not be in the result of the number variable.

Upvotes: 0

Views: 1201

Answers (2)

aschipfl
aschipfl

Reputation: 34899

Probably the easiest and most flexible method is to use the findstr command:

@echo off
set "_VALUE=%~1" & rem // (take value from first command line argument)

cmd /V /C echo(!_VALUE!| > nul findstr /R /X ^
    /C:"00*" /C:"[-+]00*" ^
    /C:"[123456789][0123456789]*" ^
    /C:"[-+][123456789][0123456789]*" ^
    && echo The value "%_VALUE%" is numeric.

You can specify multiple search strings one of which must match for the value to be considered as numeric.

The extra cmd instance is intended to enable delayed expansion (due to /V), which is needed to be able to echo every arbitrary string even with unbalanced quotation marks and special characters, like ^, &, for instance. If such cannot occur, you may replace the portion cmd /V /C echo(!_VALUE! by echo(%_VALUE%.

Upvotes: 0

John Boe
John Boe

Reputation: 3611

set "$=0" &if defined $ if !$! equ +!$! echo. isNumber: '!$!'
set "$=NaN" &if defined $ if !$! equ +!$! echo. isNumber: '!$!'

if "%VAR%" neq "" if %VAR% equ +%VAR% echo. %VAR% is a number.

Solution by Ed Dyreen, thanks!

Upvotes: 1

Related Questions