JSI Tip 10600. How can I extract the numeric characters from a string?


I have scripted OnlyNumeric.bat to extract the numeric characters from a string.

The syntax for using OnlyNumeric.bat is:

call OnlyNumeric String NumericVariableName

Where:

<b>String</b>              is the string that you wish to parse.

<b>NumericVariableName</b> is a <a href="/article/jsifaq/jsi-tip-5535-how-can-i-cause-a-called-batch-file-to-return-a-call-directed-environment-variable-.aspx">call directed environment variable</a> that will contain the numeric characters in <b>String</b>.

Example

If the variable telephoneNumber contained 1 (800) 555-1212, then:

call OnlyNumeric %telephoneNumber% NumTelNo

would set the NumTelNo variable to 18005551212.

NOTE: If String contains no numeric characters, then NumericVariableName will be undefined.

NOTE: See How can I update all users telephone number to contain only numeric characters?

OnlyNumeric.bat contains:

@echo off
if \{%2\}==\{\} @echo Syntax: OnlyNumeric String NumericVariableName&goto :EOF
if exist "%TEMP%\OnlyNumeric.vbs" goto doit
@echo.dim str, newstr, num, c1, c2>"%TEMP%\OnlyNumeric.vbs"
@echo.Set objshell = CreateObject("WScript.Shell")>>"%TEMP%\OnlyNumeric.vbs"
@echo.Set objArgs = WScript.Arguments>>"%TEMP%\OnlyNumeric.vbs"
@echo.str=objArgs(0)>>"%TEMP%\OnlyNumeric.vbs"
@echo.num = Len(str)>>"%TEMP%\OnlyNumeric.vbs"
@echo.For I = 1 To num>>"%TEMP%\OnlyNumeric.vbs"
@echo. c1 = Mid(str, I, 1)>>"%TEMP%\OnlyNumeric.vbs"
@echo. if c1 ^>= "0" and c1 ^>"%TEMP%\OnlyNumeric.vbs"
@echo.  c2 = c2 ^& c1>>"%TEMP%\OnlyNumeric.vbs"
@echo. end if>>"%TEMP%\OnlyNumeric.vbs"
@echo.Next>>"%TEMP%\OnlyNumeric.vbs"
@echo.Wscript.Echo c2>>"%TEMP%\OnlyNumeric.vbs"
:doit
set %2=
for /f "Tokens=*" %%a in ('cscript.exe //nologo "%TEMP%\OnlyNumeric.vbs" %1') do (
 set %2=%%a
)



Please or Register to post comments.

IT/Dev Connections

Las Vegas
September 30th - October 4th

Paul ThurottYou'll have the opportunity to experience:
• The Microsoft
Technology Roadmap
• Office 365 Implementation
• Hyper-V Optimizing
• Windows 8 Deployment
and much more!

Come See Paul Thurrott & Rod Trent in Person!

Early Registration Now Open

Upcoming Training

Mastering System Center 2012

During over 6 hours of training you can join John Savill from your computer as he will walk you through the key components and capabilities of System Center 2012, what’s involved in using the components, and the benefit they can bring to your environment.

Register Now

Current Issue

May 2013 - The NameTranslate object is useful when you need to translate Active Directory object names between different formats, but it's awkward to use from PowerShell. Here's a PowerShell script that eliminates the awkwardness.

CURRENT ISSUE / ARCHIVE / SUBSCRIBE

Windows Forums

Get answers to questions, share tips, and engage with the Windows Community in our Forums.