Subz

[Solved] StringRegExp split using muliple criteria

9 posts in this topic

#1 ·  Posted (edited)

Does anyone know how to split a string using multiple delimiters, returning both the values and delimiters withing the Array using StringRegExp?  For example:

;~ Split on " Not ", " And ", " Or "
$sString = ' Not $a = 1 And $b = 2 Or $b = 3'
$aArray = StringRegExp($sString,...)
;~ Returned Results
$aArray[0] = '$a = 1'
$aArray[1] = 'And'
$aArray[2] = '$b = 2'
$aArray[3] = 'Or'
$aArray[4] = '$b = 3'

At the moment I'm using

Local $aArray1 = StringRegExp($sString, '(?i) Or | And | Not ', 3)

Creating a new array using string split and then joining the two arrays together again

Local $aArray1 = StringSplit(StringRegExpReplace($sString, '(?i) Or | And | Not ', '******'), '******', 3)

Unfortunately regular expression isn't my forte.

Edited by Subz
Solved

Share this post


Link to post
Share on other sites



That isn't as easy as you seem to think, in the general case. A condition can be any valid AutoIt expression, which can be fairly complex in the real world.

To achieve what you want (again, in the general case), you need a parser. It is possible to build a complete AutoIt grammar parser using regexp but that task isn't for the faint heated.

For instance, how would you break down the following condition:

$a > 5 Or ($b = ($x ? (Not $c Or $d) : $e) And ($f Or Not _MyFct($g - 4, ' Not And Or Game', $h And Not $i) Or (Not $k Or ($l And Not $m)))) Or ($n Or $o And Not $n And $o)

Agreed, it's a little bit extreme but you must be prepared to eat that (again in the general case).

If your use case is simpler, please specify it more clearly by making explicit the grammar you want to process.


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)

Share this post


Link to post
Share on other sites

@jchd Thanks for the response, this is part of a software script I wrote and as mentioned it works fine, but thought there may have been a better alternative to my current method.  Basically I use SCCM database to write an Ini file with uninstall keys for a particular software product, I can add additional conditions to this ini.  I then call this during the start of the script to determine which criteria the system matches and to perform certain actions based upon that.

The SWQuery key is what I'm trying to put into an array, I add an "If" during the function, replace each Qryxx using the Queries section and execute the string.  I hope that makes sense, please let me know if you would like me to clarify.

Here is an example Ini File

;~ Upgrade older versions are present
[Upgrade Software Name]
SWQuery = Qry01 Or Qry02 Or Qry03 And Qry04

;~ New Install no other versions are present
[Install Software Name]
SWQuery = Qry01 = '' Or Qry02 = '' Or Qry03 = '' And Qry04

[Queries]
Qry01 = RegRead('HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\{Guid}.01', 'DisplayVersion')
Qry02 = RegRead('HKLM64\Software\Microsoft\Windows\CurrentVersion\Uninstall\{Guid}.01', 'DisplayVersion')
Qry03 = RegRead('HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\{Guid}.02', 'DisplayVersion')
Qry04 = @OSArch = 'x64'

 

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

This ?

Local $sSWQueryUpdate = IniRead("test.ini", "Upgrade Software Name", "SWQuery", "error")
Local $sSWQueryInstall = IniRead("test.ini", "Install Software Name", "SWQuery", "error")

$sSWQueryUpdate = StringRegExpReplace($sSWQueryUpdate, "\b(Qry\d+)\b", 'Execute(IniRead("test.ini", "Queries", "$1", ""))')
ConsoleWrite($sSWQueryUpdate & @CRLF)
Local $bRresult = Execute($sSWQueryUpdate)
MsgBox(0, "", "Result for update: " & $bRresult)

$sSWQueryInstall = StringRegExpReplace($sSWQueryInstall, "\b(Qry\d+)\b", 'Execute(IniRead("test.ini", "Queries", "$1", ""))')
ConsoleWrite($sSWQueryInstall & @CRLF)
$bRresult = Execute($sSWQueryInstall)
MsgBox(0, "", "Result for install : " & $bRresult)

 

Edited by jguinch
1 person likes this

Share this post


Link to post
Share on other sites

Excellent thanks @jguinch that works really well, I like the logic, I just need to make sure the key prefix is "Qry" but that shouldn't be an issue.  Thanks again.

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Instead of using QRyXX for the keys, you can use a syntax like this :

SWQuery = %Query1% Or %Q2% Or %query_03% And %Qry04%

and a code like this :

$sSWQueryUpdate = StringRegExpReplace($sSWQueryUpdate, "%([^%]+)%", 'Execute(IniRead("test.ini", "Queries", "$1", ""))')

 

Edited by jguinch
1 person likes this

Share this post


Link to post
Share on other sites

@jguinch Is this the best way to split the string from your last post, what I would like to do is execute each one of the expressions individually prior to running the full expression.  The return values will be logged and if we want to determine why a machine failed to install or upgrade we can view which expressions the system failed on.  Hope that makes sense :)  While the below works I'm not sure if this is the best pattern,

#include <Array.au3>
Local $sSWQueryUpdate = IniRead("filename.ini", "Upgrade Software Name", "SWQuery", "error")
$sSWQueryUpdate = StringRegExpReplace($sSWQueryUpdate, "%([^%]+)%", 'Execute(IniRead("filename.ini", "Queries", "$1", ""))')
$aSWQueryUpdate = StringSplit(StringRegExpReplace($sSWQueryUpdate, '( And | Or | Not )', '|'), '|')
_ArrayDisplay($aSWQueryUpdate)

 

Share this post


Link to post
Share on other sites

It's not easy to answer because it depends of the complexity of the queries (as said JCHD).

The following expression returns True :

If (1=1 Or 2=3) And 4=4

Apparently you don't need to know that 2=3 is False because the whole condition returns True.

If you want to check each condition before execution, I would do that :

;~ Upgrade older versions are present
[Upgrade Software Name]
SWQuery = (%Qry01% Or %Qry02% Or %Qry03%) And %Qry04%

;~ New Install no other versions are present
[Install Software Name]
SWQuery = (%Qry01% Or %Qry02% Or %Qry03%) And %Qry04%

[Queries]
Qry01 = RegRead('HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\{Guid}.01', 'DisplayVersion') = ''
Qry02 = RegRead('HKLM64\Software\Microsoft\Windows\CurrentVersion\Uninstall\{Guid}.01', 'DisplayVersion') = '' 
Qry03 = RegRead('HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\{Guid}.02', 'DisplayVersion') = ''
Qry04 = @OSArch = 'x64'
;~ #Include <Array.au3>

Local $sSWQueryUpdate = IniRead("test.ini", "Upgrade Software Name", "SWQuery", "error")
Local $sSWQueryInstall = IniRead("test.ini", "Install Software Name", "SWQuery", "error")

$aSWQueryUpdate = StringRegExp($sSWQueryUpdate, "%([^%]+)%", 3) ; extract the query's variables
Local $sSWQueryUpdateBoolean = $sSWQueryUpdate

;~ _ArrayDisplay($aSWQueryUpdate)
For $i = 0 To UBound($aSWQueryUpdate) - 1
    $sCondition = IniRead("test.ini", "Queries", $aSWQueryUpdate[$i], "error") ; read the condition
    $vRes = Execute($sCondition) ? True : False ; executes the condition
    $sSWQueryUpdateBoolean = StringRegExpReplace($sSWQueryUpdateBoolean, "%" & $aSWQueryUpdate[$i] & "%", $vRes) ; replace each query by its result
    ConsoleWrite("Condition " & $aSWQueryUpdate[$i] & " : " & ($vRes ? "SUCCESS" : "FAILURE") & @CRLF )
Next

ConsoleWrite($sSWQueryUpdateBoolean & @CRLF) ; Boolean condition
$iRes = Execute($sSWQueryUpdateBoolean)
ConsoleWrite("Result : " & $iRes)

 

1 person likes this

Share this post


Link to post
Share on other sites

Thanks jguinch much appreciated.

Share this post


Link to post
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

  • Similar Content

    • Robinson1
      By Robinson1
      Well the plan is to use the power of regular expressions engine of AutoIT for patching binary data.
      Something like this: StringRegExp( $BinaryData,  "(?s)\x55\x8B.."
       
      <cut> ... Okay straight to question/problem
      ... certain bytes that are in the range from 0x80 to 0xA0 won't match.
      Hmm seem to be a char encoding problem. In detail these are 27 chars: 0x80, 0x82~8C, 0x8E, 0x91~9C, 0x9E,0x9F
      Here's a small code snippet to explore / explain this problem:
      #include "StringConstants.au3" $TestData = BinaryToString("0x7E7F808182") ;Okay $match = StringRegExp( $TestData ,'\x7E' ,$STR_REGEXPARRAYFULLMATCH) ConsoleWrite('@extended = ' & @extended & ' $match = ' & $match & @CRLF) ;Okay $match = StringRegExp( $TestData ,'\x7F' ,$STR_REGEXPARRAYFULLMATCH) ConsoleWrite('@extended = ' & @extended & ' $match = ' & $match & @CRLF) ;Error no match $match = StringRegExp( $TestData ,'\x80' ,$STR_REGEXPARRAYFULLMATCH) ConsoleWrite('@extended = ' & @extended & ' $match = ' & $match & @CRLF) ;Okay $match = StringRegExp( $TestData ,'\x81' ,$STR_REGEXPARRAYFULLMATCH) ConsoleWrite('@extended = ' & @extended & ' $match = ' & $match & @CRLF) ;Error no match $match = StringRegExp( $TestData ,'\x82' ,$STR_REGEXPARRAYFULLMATCH) ConsoleWrite('@extended = ' & @extended & ' $match = ' & $match & @CRLF) ;~ output: ;~ @extended = 2 $match = ;~ @extended = 3 $match = ;~ @extended = 0 $match = 1 ;~ @extended = 5 $match = ;~ @extended = 0 $match = 1 Hmm what to do? Go back and use the 'numberstring monster' implementation or just omit that range of 'unsafe bytes'. What is the root of this problem?
      Any idea how to fix this?
       
      Update: Okay I know a byte is not a character.
      But StringRegExp operates on String and so character level.
      Okay as long as you stay at Ansi encoding and only use /x00 - /X7F in the search pattern using  StringRegExp works well to search for binary data.
      What bytes can be matched that are in the range from /X7F - /xFF is also depending on the code page.
      So this avoid to search for bytes in the range from 0x80-0xa0 only applies to Germany.
      I just change this country setting:

      to Thai and now near all bytes from /X7F - /xFF fails to match.
    • Carm01
      By Carm01
      Hello,
      I have spent the past day fooling with StringRegExp to no avail attempting to get what would be a simple solution to an issue using StringRegExp.
      I will post the code in a sec. The string 'Java x Update y' where x and y are numeric values ONLY if a letter is mixed in anywhere then it should fail. I have been able to successfully deal with the x value so if x = 1234 or a1234 or 1a234 or 1234a would result in a fail if 'a' was in the string. However, when y = 1a234 then I get an output of 1 and when y = 1234a then the output = 1234 when both should fail. I am probably overlooking something simple and in looking through all the material and experimenting I am unable to figure it out and my experience with stringregexp and trying to find examples of this proved difficult. If someone could assist or point me to a thread ? Here is my code ; prob a simple fix. I am also trying to avoid white spaces.
      Thanks in advance
      #include <array.au3> $aArray = StringRegExp('Java 3009 Update 1a21', '(?i)Java (\d+) Update (\d+)', $STR_REGEXPARRAYGLOBALMATCH) If @error Then Exit _ArrayDisplay($aArray)  
    • VIP
      By VIP
      Need help to make function better  with full infomation
      #include <Array.au3> #include <File.au3> _TEST(@ScriptFullPath) _TEST("A:") _TEST("A:\B.c") _TEST("D:\E\F\") _TEST("G:\H/../J.k/") _TEST("M:\N\k..J.k") _TEST("D:\E\F\..\G\G\I..J.K.M") Func _TEST($sFilePath) Local $sDrive = "", $sFullPathDir = "", $sDirPath = "", $sDirName = "", $sFileName = "", $sFileNameExt = "", $sExtension = "", $sExt = "" Local $aPathSplit = _PathSplitByRef($sFilePath, $sDrive, $sFullPathDir, $sDirPath, $sDirName, $sFileName, $sFileNameExt, $sExtension, $sExt) ConsoleWrite("!Path IN : " & $sFilePath & @CRLF) ; C:\Windows\System32\etc\hosts.exe ConsoleWrite("- Driver : " & $sDrive & @CRLF) ; C: ConsoleWrite("- DirPath : " & $sFullPathDir & @CRLF) ; C:\Windows\System32\etc\etc ConsoleWrite("- DirPath : " & $sDirPath & @CRLF) ; \Windows\System32\etc\ ConsoleWrite("- DirName : " & $sDirName & @CRLF) ; etc ConsoleWrite("- FileName : " & $sFileName & @CRLF) ; hosts ConsoleWrite("- FileNameExt: " & $sFileNameExt & @CRLF) ; hosts.exe ConsoleWrite("- Extension : " & $sExtension & @CRLF) ; .exe ConsoleWrite("- Ext : " & $sExt & @CRLF & @CRLF) ; exe ;~ ConsoleWrite("!Path IN : " & $aPathSplit[0] & @CRLF) ; C:\Windows\System32\etc\hosts.exe ;~ ConsoleWrite("- Driver : " & $aPathSplit[1] & @CRLF) ; C: ;~ ConsoleWrite("- DirPath : " & $aPathSplit[2] & @CRLF) ; C:\Windows\System32\etc\etc ;~ ConsoleWrite("- DirPath : " & $aPathSplit[3] & @CRLF) ; \Windows\System32\etc\ ;~ ConsoleWrite("- DirName : " & $aPathSplit[4] & @CRLF) ; etc ;~ ConsoleWrite("- FileName : " & $aPathSplit[5] & @CRLF) ; hosts ;~ ConsoleWrite("- FileNameExt: " & $aPathSplit[6] & @CRLF) ; hosts.exe ;~ ConsoleWrite("- Extension : " & $aPathSplit[7] & @CRLF) ; .exe ;~ ConsoleWrite("- Ext : " & $aPathSplit[8] & @CRLF) ; exe ;~ _ArrayDisplay($aPathSplit, "_PathSplit of " & $sFilePath) EndFunc ;==>_TEST Func _PathSplitByRef($sFilePath, ByRef $sDrive, ByRef $sFullPathDir, ByRef $sDirPath, ByRef $sDirName, ByRef $sFileName, ByRef $sFileNameExt, ByRef $sExtension, ByRef $sExt) If StringInStr($sFilePath,"..") Then $sFilePath=_PathFull($sFilePath) Local $aPartOfPath=StringRegExp($sFilePath, "^\h*((?:\\\\\?\\)*(\\\\[^\?\/\\]+|[A-Za-z]:)?(.*[\/\\]\h*)?((?:[^\.\/\\]|(?(?=\.[^\/\\]*\.)\.))*)?([^\/\\]*))$", $STR_REGEXPARRAYMATCH) ;~ If @error Then ReDim $aPartOfPath[9] ;~ $aPartOfPath[0] = $sFilePath ;~ EndIf $aPartOfPath[0] = $sFilePath ; C:\Windows\System32\etc\hosts.exe $sDrive = $aPartOfPath[1] ; C: $sFullPathDir = $aPartOfPath[1] & $aPartOfPath[2] ; C:\Windows\System32\etc If StringLeft($aPartOfPath[2], 1) == "/" Then $sDirPath = StringRegExpReplace($aPartOfPath[2], "\h*[\/\\]+\h*", "\/") Else $sDirPath = StringRegExpReplace($aPartOfPath[2], "\h*[\/\\]+\h*", "\\") EndIf $aPartOfPath[2] = $sFullPathDir ; C:\Windows\System32\etc $sDirName=StringReplace($sDirPath,"\","") $sDirName=StringReplace($sDirPath,"/","") $sFileName = $aPartOfPath[3] ; hosts $aPartOfPath[5] = $sFileName ; hosts $sExtension = $aPartOfPath[4] ; .exe $aPartOfPath[7] = $sExtension ; .exe $aPartOfPath[3] = $sDirPath ; \Windows\System32\etc\ $aPartOfPath[4] = $sDirName ; etc $aPartOfPath[6] = $sFileName & $sExtension ; hosts.exe $sFileNameExt = $aPartOfPath[6] ; hosts.exe $sExt = StringReplace($sExtension,".","") ; exe $aPartOfPath[8] = $sExt ; exe Return $aPartOfPath EndFunc ;==>_PathSplitByRef  
    • VIP
      By VIP
      Hi,
      I need help string RegEx to get string from CREATE to GO
      #include <StringConstants.au3> ;~ Global $fileSQL1 = @ScriptDir & "\fileSQL1.sql" ;~ Global $fileSQL2 = @ScriptDir & "\fileSQL2.sql" Global $tmpSQLfile = @TempDir & "\tmpFile.sql" OnAutoItExitRegister("_OnExit") _SetTMPsql() If Not FileExists($tmpSQLfile) Then OnAutoItExitUnRegister("_OnExit") Exit MsgBox(48, "/!\", "File: " & $tmpSQLfile & @CRLF & " is not Exists!", 3) EndIf Global $ContentSQLfile = FileRead($tmpSQLfile) _Start() Func _Start() Local $aArray, $iOffset = 1, $stringRegExp = '(?i)CREATE(.*?)GO' While 1 $aArray = StringRegExp($ContentSQLfile, $stringRegExp, $STR_REGEXPARRAYMATCH, $iOffset) If @error Then MsgBox(48, "StringRegExp Error " & @error, "+> StringRegExp: " & $stringRegExp & @CRLF & @CRLF & "=> With STRING:" & @CRLF & @CRLF & $ContentSQLfile) ExitLoop EndIf $iOffset = @extended For $i = 0 To UBound($aArray) - 1 MsgBox(0, "RegExp Test with Option 1 - " & $i, $aArray[$i]) Next WEnd EndFunc ;==>_Start Func _SetTMPsql() Local $tmpSQLContent = "" $tmpSQLContent &= "USE [Master]" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "" & @CRLF $tmpSQLContent &= "CREATE DATABASE [Sales] ON PRIMARY " & @CRLF $tmpSQLContent &= "( NAME = N’Sales’, FILENAME = N’\FSASQLDBSales.mdf’ , " & @CRLF $tmpSQLContent &= " SIZE = 2GB , MAXSIZE = 8GB, FILEGROWTH = 1GB )" & @CRLF $tmpSQLContent &= "LOG ON " & @CRLF $tmpSQLContent &= "( NAME = N’Sales_log’, FILENAME = N’\FSASQLDBSales_log.ldf’ , " & @CRLF $tmpSQLContent &= " SIZE = 1GB , MAXSIZE = 2GB , FILEGROWTH = 10%)" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "" & @CRLF $tmpSQLContent &= "USE [Sales]" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "" & @CRLF $tmpSQLContent &= "-- Table Product" & @CRLF $tmpSQLContent &= "CREATE TABLE [dbo].[Product]" & @CRLF $tmpSQLContent &= "(" & @CRLF $tmpSQLContent &= " [ProductId] [uniqueidentifier] DEFAULT NEWID() NOT NULL," & @CRLF $tmpSQLContent &= " [ProductName] [nchar](50) NULL," & @CRLF $tmpSQLContent &= " [ProductDescription] [nchar](3000) NULL," & @CRLF $tmpSQLContent &= " [ProductPrice] MONEY NULL" & @CRLF $tmpSQLContent &= ") ON [PRIMARY]" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "" & @CRLF $tmpSQLContent &= "-- Table Sales" & @CRLF $tmpSQLContent &= "CREATE TABLE [dbo].[Sales]" & @CRLF $tmpSQLContent &= "( " & @CRLF $tmpSQLContent &= " [SaleId] [uniqueidentifier] DEFAULT NEWID() NOT NULL," & @CRLF $tmpSQLContent &= " [SaleName] [nchar](50) NULL," & @CRLF $tmpSQLContent &= " [SaleInfo] [nchar](3000) NULL," & @CRLF $tmpSQLContent &= " [SaleMoney] MONEY NULL" & @CRLF $tmpSQLContent &= ") ON [PRIMARY]" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "" & @CRLF $tmpSQLContent &= "SET ANSI_NULLS ON" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "SET QUOTED_IDENTIFIER ON" & @CRLF $tmpSQLContent &= "GO" & @CRLF $tmpSQLContent &= "" & @CRLF $tmpSQLContent &= "-- The End" & @CRLF Local $hOpen = FileOpen($tmpSQLfile, 2 + 8 + 128) FileWrite($hOpen, $tmpSQLContent) Return FileClose($hOpen) EndFunc ;==>_SetTMPsql Func _OnExit() Exit FileDelete($tmpSQLfile) EndFunc ;==>_OnExit  
      mikell
       
    • david1337
      By david1337
      Hi guys
      I hope you can help me out with this one.
      I have a text file "test.txt" which could contain something like this:
      __________________________________________________________
      fiw
      eqw
      sdg
      xcv
      __________________________________________________________
      Each string has it's own line.
       
      I use this script to find a string in the text file.
      In this example, the string I am looking for is "iw".
      The string "fiw" makes it believe that "iw" is found in the file. How can I avoid this?
      I want it only to return EXACT results.
       
      $string = "iw" $File = FileOpen("test.txt", 0) $ReadFile = FileRead($File) FileClose($File) If StringRegExp(StringLower($ReadFile), StringLower($string)) Then MsgBox(0,"",$string & " is found in the file") Exit Else MsgBox(0,"",$string & " is not found in the file") Exit EndIf