Jump to content

Regexp to determine if string contains number


Recommended Posts

I remember that a few months ago someone (I think ProgAndy) posted a regexp which determines whether a string contains a number, including a floating-point number.

I can't find it on the forum. Please would someone point me to it.

Spoiler

CDebug Dumps values of variables including arrays and DLL structs, to a GUI, to the Console, and to the Clipboard

 

Link to comment
Share on other sites

  • Moderators

c.haslam,

Not the one for which you are looking, but I have used this RegEx with success:

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <EditConstants.au3>

$iMaxDecimalCount = 2

$hGui = GUICreate('?????? ?????', 220, 180)
$cInput = GUICtrlCreateInput('', 10, 10, 200, 20);, -1, $WS_EX_STATICEDGE)
GUISetState()
GUIRegisterMsg($WM_COMMAND, 'WM_COMMAND')

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch

WEnd



Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
    If $ilParam <> GUICtrlGetHandle($cInput) Then Return $GUI_RUNDEFMSG
    Local $nNotifyCode, $nID, $sText

    $nNotifyCode = BitShift($iwParam, 16)
    Static $sPrevText = ''

    Switch $nNotifyCode

        Case $EN_CHANGE
            $sText = GUICtrlRead($cInput)
            If Not StringRegExp($sText, '^(-)?(\d*\.\d{0,' & $iMaxDecimalCount & '}|(\d{1,3}|^)(?:,\d{0,3})+(?:(?<=\d{3})\.\d{0,' & $iMaxDecimalCount & '})?|\d*)$') Then
                GUICtrlSetData($cInput, $sPrevText)
            Else
                $sPrevText = $sText

            EndIf

    EndSwitch



    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_COMMAND

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Thank you both.

I thought I had stored ProgAndy's code somewhere on my PC. I had, in an unlikely place. His regexp seems to work for all formats of number:

Func IsNumeric($vValue)
    Return (StringRegExp($vValue, "(^[+-]?[0-9]+\.?[0-9]*$|^0x[0-9A-Fa-f]{1,8}$|^[0-9]+\.?[0-9]*[Ee][+-][0-9]+$)") = 1)
 EndFunc  ;==>_IsNumeric

 

Spoiler

CDebug Dumps values of variables including arrays and DLL structs, to a GUI, to the Console, and to the Clipboard

 

Link to comment
Share on other sites

c.haslam,

Run the following and note the results...

ConsoleWrite(IsNumeric('75.') & @CRLF)
ConsoleWrite(mikell('75.') & @CRLF)

Func IsNumeric($vValue)
    Return (StringRegExp($vValue, "(^[+-]?[0-9]+\.?[0-9]*$|^0x[0-9A-Fa-f]{1,8}$|^[0-9]+\.?[0-9]*[Ee][+-][0-9]+$)") = 1)
EndFunc  ;==>_IsNumeric



func mikell($num)
    return StringRegExp($num, '^\d*\.?\d+$') = 1
endfunc

kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Link to comment
Share on other sites

#include <Array.au3>

Local $aNb = [ _
    ["0x0", 0, 0, 0], _
    ["0x01", 0, 0, 0], _
    ["0x012", 0, 0, 0], _
    ["0x0123", 0, 0, 0], _
    ["0x01234", 0, 0, 0], _
    ["0x012345", 0, 0, 0], _
    ["0x0123456", 0, 0, 0], _
    ["0x01234657", 0, 0, 0], _
    ["0x012346578", 0, 0, 0], _
    ["0x0123465789", 0, 0, 0], _
    ["0x0123465789A", 0, 0, 0], _
    ["0x0123465789AB", 0, 0, 0], _
    ["0x0123465789ABC", 0, 0, 0], _
    ["0x0123465789ABC", 0, 0, 0], _
    ["0x0123465789ABCD", 0, 0, 0], _
    ["0x0123465789ABCDE", 0, 0, 0], _
    ["0x0123465789ABCDEF", 0, 0, 0], _
    ["123", 0, 0, 0], _
    ["+123", 0, 0, 0], _
    ["-123", 0, 0, 0], _
    ["123.", 0, 0, 0], _
    ["+123.", 0, 0, 0], _
    ["-123.", 0, 0, 0], _
    [".123", 0, 0, 0], _
    ["+.123", 0, 0, 0], _
    ["-.123", 0, 0, 0], _
    ["1.23", 0, 0, 0], _
    ["+1.23", 0, 0, 0], _
    ["-1.23", 0, 0, 0], _
    ["123e4", 0, 0, 0], _
    ["+123e4", 0, 0, 0], _
    ["-123e4", 0, 0, 0], _
    ["123.e4", 0, 0, 0], _
    ["+123.e4", 0, 0, 0], _
    ["-123.e4", 0, 0, 0], _
    [".123e4", 0, 0, 0], _
    ["+.123e4", 0, 0, 0], _
    ["-.123e4", 0, 0, 0], _
    ["1.23e4", 0, 0, 0], _
    ["+1.23e4", 0, 0, 0], _
    ["-1.23e4", 0, 0, 0], _
    ["123e+4", 0, 0, 0], _
    ["+123e+4", 0, 0, 0], _
    ["-123e+4", 0, 0, 0], _
    ["123.e+4", 0, 0, 0], _
    ["+123.e+4", 0, 0, 0], _
    ["-123.e+4", 0, 0, 0], _
    [".123e+4", 0, 0, 0], _
    ["+.123e+4", 0, 0, 0], _
    ["-.123e+4", 0, 0, 0], _
    ["1.23e+4", 0, 0, 0], _
    ["+1.23e+4", 0, 0, 0], _
    ["-1.23e+4", 0, 0, 0], _
    ["123e-4", 0, 0, 0], _
    ["+123e-4", 0, 0, 0], _
    ["-123e-4", 0, 0, 0], _
    ["123.e-4", 0, 0, 0], _
    ["+123.e-4", 0, 0, 0], _
    ["-123.e-4", 0, 0, 0], _
    [".123e-4", 0, 0, 0], _
    ["+.123e-4", 0, 0, 0], _
    ["-.123e-4", 0, 0, 0], _
    ["1.23e-4", 0, 0, 0], _
    ["+1.23e-4", 0, 0, 0], _
    ["-1.23e-4", 0, 0, 0] _
]

For $i = 0 To UBound($aNb) - 1
    $aNb[$i][1] = IsNumeric($aNb[$i][0])
    $aNb[$i][2] = mikell($aNb[$i][0])
    $aNb[$i][3] = jchd($aNb[$i][0])
Next

_ArrayDisplay($aNb, 'What is numeric?', "", 0, Default, 'String|IsNumeric|mikell|jchd')

Func IsNumeric($vValue)
    Return (StringRegExp($vValue, "(^[+-]?[0-9]+\.?[0-9]*$|^0x[0-9A-Fa-f]{1,8}$|^[0-9]+\.?[0-9]*[Ee][+-][0-9]+$)") = 1)
EndFunc  ;==>_IsNumeric

func mikell($num)
    return StringRegExp($num, '^\d*\.?\d+$') = 1
endfunc

func jchd($num)
    return StringRegExp($num, '(?ix)^(0x[[:xdigit:]]{1,8}? | [+-]?\d*\.?\d*(?:E[+-]?\d+)?)$') = 1
endfunc

Signed hex values are uncommon but it would be trivial to deal with.

Edited by jchd
Cut & paste typo in regexp

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

You're a shy lovely cat...

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

You're a shy lovely cat...

I am not fooled by that image.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Because AutoIt accepts e.g. 1.2e5 I would make one change  in IsNumeric's regexp:

"(^[+-]?[0-9]+\.?[0-9]*$|^0x[0-9A-Fa-f]{1,8}$|^[0-9]+\.?[0-9]*[Ee][+-]?[0-9]+$)"

 

Spoiler

CDebug Dumps values of variables including arrays and DLL structs, to a GUI, to the Console, and to the Clipboard

 

Link to comment
Share on other sites

Buy a helmet?

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

It was part of a much more involved expression and I didn't remind/notice it was there. There was also an optional parasitic closing }.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Thanks for explaining. I thought that you knew even more than I thought you did about regexps, which is already much more than I know!

BTW for my current project, which is experimental (!), I have mostly abandoned regexps (except for detecting whether a line of code contains a call to a function). I am heeding your advice to keep regexps as simple as possible. Instead, I am using a function that I wrote. It does the same as StringSplit("string", "delimiters",$STR_CHRSPLIT + $STR_NOCOUNT (2)), but also returns the delimiters that it found, and can skip literal strings:

; Like StringSplit except returns delimiters and can skip quotations
; if first char in str is a separator, wordsVec[0] = ''
; if last char in str is a separator, last el of wordsVec = ''
Func StrParseDelims($str,$seps, ByRef $delimsVec,$bSkipQuotations=False)
    Local $wordP=1,$wordPs='',$wordLens='',$q=0,$p,$delims=''
    While True
        Local $ch = StringMid($str,$wordP,1)
        If $bSkipQuotations and ($ch='"' or $ch="'") Then
            $p = StringInStr($str,$ch,1,1,$wordP+1)
        Else
            $p = $wordP
        EndIf
        Local $pdelim = StrScanEq($str,$p,$seps)
        $wordPs &= '?'&$wordP
        $wordLens &= '?'&($pdelim-$wordP)
        $q += 1
        If $pdelim>StringLen($str) Then ExitLoop
        $delims &= StringMid($str,$pdelim,1)
        $wordP =  $pdelim + 1
    WEnd
    Local $wordsVec[$q]
    Local $posVec = StringSplit(StringMid($wordPs,2),'?',2) ; char, 0-based
    Local $wordLensVec = StringSplit(StringMid($wordLens,2),'?',2)
    For $i = 0 to $q-2
        $wordsVec[$i] = StringMid($str,$posVec[$i],$wordLensVec[$i])
    Next
    If $wordLensVec[$q-1]<>0 Then
        $wordsVec[$q-1] = StringMid($str,$posVec[$q-1],$wordLensVec[$q-1])
    EndIf
    $delimsVec = StringSplit($delims,'',2)
    Return $wordsVec
EndFunc

; Get pos of first of $chs chars in $str after pos $pst
Func StrScanEq($str,$pst,$chs)
    Local $ret = 99999
    Local $chsVec =  StringSplit($chs,'',2) ; char, 0-based
    For $el In $chsVec
        Local $p = StringInStr($str,$el,1,1,$pst)   ; case-sens, 1st
        If $p<>0 and $p<$ret Then
            $ret = $p
        EndIf
    Next
    If $ret=99999 Then
        $ret = StringLen($str) + 1
    EndIf
    Return $ret
EndFunc

 

Edited by c.haslam
Spoiler

CDebug Dumps values of variables including arrays and DLL structs, to a GUI, to the Console, and to the Clipboard

 

Link to comment
Share on other sites

I'm afraid I don't fully get it/ Can you give a spec or at least provide a few couples of typical or pathalogical inputs and corresponding expected output?

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Here is a (contrived) simple example:

Local $code = "Local $gNowSecs = NowSecs($a,34)"
Local $delimsVec
Local $wordsVec = StrParseDelims($code,' (,)',$delimsVec)
For $i = 0 to UBound($wordsVec)-2
    If StringLeft($wordsVec[$i],1)='$' Then
        Switch $delimsVec[$i]
            Case ' '
                Local $returns = $wordsVec[$i]
            Case ',',')'
                Local $param = $wordsVec[$i]
        EndSwitch
    ElseIf $delimsVec[$i]='(' Then
        Local $function = $wordsVec[$i]
    EndIf
Next
MsgBox(0,'','$returns '&$returns&' $function '&$function&' $param '&$param)

 

Spoiler

CDebug Dumps values of variables including arrays and DLL structs, to a GUI, to the Console, and to the Clipboard

 

Link to comment
Share on other sites

I don't believe this can be made robust enough for the general real-world case. I tried:

Local $code = "Local $gNowSecs = Mod(NowSecs($a,34), 5)"
Local $code = "Local $gNowSecs = Mod(NowSecs($a,'34'), 5)"
Local $code = "Local $gNowSecs = 'Mod(NowSecs($a,''34''), 5)'"
Local $code = "Local $gNowSecs = String('Mod(NowSecs($a,''34''), 5)')"

but the result didn't change. Also this falls apart:

Local $code = "Local $gNowSecs = NowSecs('$a',34)"
Local $code = "Local $gNowSecs = NowSecs(""$a"",34)"

What's the actual goal?

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

I just had to add to this thread, if you want to learn regexp then regexr.com is an awesome place to start. You can paste what you want to match into the main box (html, chat logs, whatever) and then try to make a pattern at the top and it will try to match your pattern on the fly

You can also paste one of the patterns you see here in the top bar and hover your mouse over the various elements, and it will give you a description of what each one does

It is always my go-to tool when trying to make regular expressions, and is well worth bookmarking.

Edited by corgano

0x616e2069646561206973206c696b652061206d616e20776974686f7574206120626f64792c20746f206669676874206f6e6520697320746f206e657665722077696e2e2e2e2e

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...