The script below attempts to determine if a string can be considered HEX if analyzed via Regex. The idea is to match the entire string as a variable to the regex pattern. It should fail if any item in the string if not in the pattern, i.e. 0-9, A-F, a-f, and include spaces... Seems to work
;Winbatch 2025A - Regex Check if string is Hex
;Stan Littlefield, 12/02/2025
;========================================================================
IntControl(73,1,0,0,0)
gosub udfs
ObjectClrOption( 'useany', 'System')
oReg = ObjectClrNew('System.Text.RegularExpressions.Regex')
opts = ObjectClrType('System.Text.RegularExpressions.RegexOptions',1)
pattern = '^[0-9A-Fa-f\s]+$'
text = 'AD 0A'
regex()
text = '1234abcd'
regex()
text = 'ffff 12k'
regex()
text = '#h AD OA'
regex()
oReg=0
Exit
;========================================================================
:WBERRORHANDLER
geterror()
Terminate(@TRUE,"Error Encountered",errmsg)
;========================================================================
:udfs
#DefineSubRoutine geterror()
wberroradditionalinfo = wberrorarray[6]
lasterr = wberrorarray[0]
handlerline = wberrorarray[1]
textstring = wberrorarray[5]
linenumber = wberrorarray[8]
errmsg = "Error: ":lasterr:@LF:textstring:@LF:"Line (":linenumber:")":@LF:wberroradditionalinfo
Return(errmsg)
#EndSubRoutine
#DefineSubRoutine regex()
matches = oReg.Matches(text,pattern,opts)
results = "is a Hex String"
if matches.Count==0
results = "is not a Hex String"
endif
Message(text,results)
Return(1)
#EndSubRoutine
Return
;========================================================================
Not saying that the below is any better. I am just adding another example of a seemingly seldom used WIL function.
;text = 'AD 0A'
;text = '1234abcd'
;text = 'ffff 12k'
text = '#h AD OA'
text2 = StrClean(text," ":@tab,"",0,1)
IsHex = StrTypeInfo(text2,0) & 128
if IsHex then Result = "is a Hex String"
else Result = "is not a Hex String"
Message(Text, Result)
exit
Dang it, I keep forgetting about StrTypeInfo. It neatly splits the difference between a plain equals comparision and full regex match. Nice.
Stan,
what does this line do?
TIA,
Kirby
oReg.CacheSize = ObjectType("ui2",30)
Quote from: kdmoyers on December 02, 2025, 10:46:47 AMStan,
what does this line do?
TIA,
Kirby
oReg.CacheSize = ObjectType("ui2",30)
The default of 15 which is the maximum number of stored regex expressions is probably sufficient, but I have always used this line, based on WIL example from Deana in Tech DB to safeguard against multiple iterations or iterations with multiple patterns. And while Tony's code is more elegant I have always looked to regex as a bigger picture.
[EDIT]: removed cache line in my code, not really needed.