WinBatch® Technical Support Forum

All Things WinBatch => WinBatch => Topic started by: spl on April 16, 2025, 04:52:59 AM

Title: fun with regex OR / Comparison
Post by: spl on April 16, 2025, 04:52:59 AM
Probably easy to break the script below, but reading the attached text file the code uses regex to determine if each line in the text file matches/partially matches or does not match the regex expression. The basis for the regex is to determine if [Name] likes/loves etc.. [condition], but does not like/hates etc.. [condition]. When run the script with read the file and pull up results in message. The script


The regex is a lot faster than a series of if's, strindex(), strsub() lines [in my opinion]. I would have liked a more definite pattern to isolate the partial matches, but that is a bit of a regex holy grail. Anyway, running, breaking, modifying the code might be something to break boredom.
IntControl(73,1,0,0,0)
gosub udfs
ObjectClrOption( 'useany', 'System')
file = Dirscript():"lines.txt"
if ! fileexist(file) Then Terminate(@TRUE,"File not Found",file)
h = FileOpen(file, "READ")
srchs = "red|orange|yellow|green|blue|indigo|violet"
pattern = "([^\s]+) \w+ (?:":srchs:"), but \w+ (?:":srchs:")+.*$"
results = ""
While @True
   line = FileRead(h)
   If line == "*EOF*" Then Break
   ;does line end in a period
   If StrScan(line, ".",strlen(line)-1,@FWDSCAN)
      line = strreplace(line,".","")
   Endif
   regex(line,pattern,results)
Endwhile
FileClose(h)

Message("COLORS (":srchs:"): Results",results)
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(line,pattern,results)
   retval = 0
   opts = ObjectClrType('System.Text.RegularExpressions.RegexOptions',1)
   oReg = ObjectClrNew('System.Text.RegularExpressions.Regex',pattern,opts)
   oReg.CacheSize = ObjectType("ui2",30)
   if oReg.IsMatch(line)
      retval = 1
      results := oReg.Match(line).Value:@CRLF
   else
      results := line:" | Partial or No Match":@CRLF
   endif
   oReg=0
   Return(retval)
#EndSubRoutine

Return