Sign in to follow this  
Followers 0
guinness

Regular expression apprecition society.

9 posts in this topic

#1 ·  Posted (edited)

Don't you just love it when a regular expression comes out on top?! I know I do..

Local $hTimer = 0

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_1('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_2('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

Func _IsSystemDrive_Test_1($sDrive)
    Local $aArray = [@HomeDrive, _
            @ProgramFilesDir, _
            @SystemDir, _
            @WindowsDir]
    For $sFilePath In $aArray
        If StringLeft($sFilePath, 1) = $sDrive Then
            Return True
        EndIf
    Next
    Return False
EndFunc   ;==>_IsSystemDrive

Func _IsSystemDrive_Test_2($sDrive)
    Return StringRegExp(@HomeDrive & '|' & @ProgramFilesDir & '|' & @SystemDir & '|' & @WindowsDir, '(?<=^|\|)(?:' & $sDrive & ')') = 1
EndFunc   ;==>_IsSystemDrive

I am no expert at regular expressions, but what I have managed to learn has proved very useful over the last couple of years.

Edited by guinness
1 person likes this

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites



101 % agree :D

BTW you can save 2 ms more by removing the '=1' which makes your code test twice (1st with the regex, 2nd by interpreting the func return)

Local $hTimer = 0

$hTimer = TimerInit()
For $i = 1 To 10000
    $s = _IsSystemDrive_Test_2('C')
Next
ConsoleWrite($s & @CRLF & TimerDiff($hTimer) & @CRLF)

$hTimer = TimerInit()
For $i = 1 To 10000
    $s = _IsSystemDrive_Test_3('C')
Next
ConsoleWrite($s & @CRLF & TimerDiff($hTimer) & @CRLF)

Func _IsSystemDrive_Test_2($sDrive)
    Return StringRegExp(@HomeDrive & '|' & @ProgramFilesDir & '|' & @SystemDir & '|' & @WindowsDir, _
        '(?<=^|\|)(?:' & $sDrive & ')') = 1
EndFunc   ;==>_IsSystemDrive

Func _IsSystemDrive_Test_3($sDrive)
    Return StringRegExp(@HomeDrive & '|' & @ProgramFilesDir & '|' & @SystemDir & '|' & @WindowsDir, _
        '(?<=^|\|)(?:' & $sDrive & ')')
EndFunc   ;==>_IsSystemDrive

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

I like it better when it does not.

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_3('C:')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

Func _IsSystemDrive_Test_3($sDrive)
    Return StringInStr(@HomeDrive , $sDrive) And StringInStr(@ProgramFilesDir , $sDrive) And StringInStr(@SystemDir , $sDrive) And StringInStr(@WindowsDir , $sDrive)
EndFunc   ;==>_IsSystemDrive
Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

Especially when the tests are fair.

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_4('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

Func _IsSystemDrive_Test_4($sDrive)
    Return StringLeft(@HomeDrive , 1) = $sDrive And StringLeft(@ProgramFilesDir , 1) = $sDrive And StringLeft(@SystemDir , 1) = $sDrive And StringLeft(@WindowsDir , 1) = $sDrive
EndFunc   ;==>_IsSystemDrive

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

Hum :blink:

JO the 2nd code is not faster than the regex, but the 1st one looks like a "learn when not to use regex" (in this particular case)

Share this post


Link to post
Share on other sites

I record the 1st function as quicker by approx 10 ms. Interesting what a small change does to alter the result.

Global $hTimer = 0
Global $aArray = [ _
 @HomeDrive, _
 @ProgramFilesDir, _
 @SystemDir, _
 @WindowsDir _
]

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_1('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_2('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

Func _IsSystemDrive_Test_1($sDrive)
    For $sFilePath In $aArray
        If StringLeft($sFilePath, 1) = $sDrive Then
            Return True
        EndIf
    Next
    Return False
EndFunc   ;==>_IsSystemDrive

Func _IsSystemDrive_Test_2($sDrive)
    Return StringRegExp($aArray[0] & '|' & $aArray[1] & '|' & $aArray[2] & '|' & $aArray[3], '(?<=^|\|)(?:' & $sDrive & ')') = 1
EndFunc   ;==>_IsSystemDrive

Share this post


Link to post
Share on other sites

Hum :blink:

JO the 2nd code is not faster than the regex, but the 1st one looks like a "learn when not to use regex" (in this particular case)

They both register faster for me.

But you're right, I've been dodging regex since I started AutoIt, I just don't get it, I've tried but it's like an alien language to me.


AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

Haha I understand now

Though your first code is a really good example of "knowing when NOT to use regex"  :)

 

Share this post


Link to post
Share on other sites

I record the 1st function as quicker by approx 10 ms. Interesting what a small change does to alter the result.

Global $hTimer = 0
Global $aArray = [ _
 @HomeDrive, _
 @ProgramFilesDir, _
 @SystemDir, _
 @WindowsDir _
]

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_1('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

$hTimer = TimerInit()
For $i = 1 To 10000
    _IsSystemDrive_Test_2('C')
Next
ConsoleWrite(TimerDiff($hTimer) & @CRLF)

Func _IsSystemDrive_Test_1($sDrive)
    For $sFilePath In $aArray
        If StringLeft($sFilePath, 1) = $sDrive Then
            Return True
        EndIf
    Next
    Return False
EndFunc   ;==>_IsSystemDrive

Func _IsSystemDrive_Test_2($sDrive)
    Return StringRegExp($aArray[0] & '|' & $aArray[1] & '|' & $aArray[2] & '|' & $aArray[3], '(?<=^|\|)(?:' & $sDrive & ')') = 1
EndFunc   ;==>_IsSystemDrive

Too many Global variables like that makes my head hurt.

_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

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
Sign in to follow this  
Followers 0

  • Similar Content

    • FroVN
      By FroVN
      Hello, i have a problem, first i create two gui , first gui use Fuction Soundplay to play the music, if the music playing in the end, it auto change a new song like playlist on soundcloud, but the problem that while i press a button in gui 1 to open gui 2 , the song when it end it not change to a new song, wait for gui 2 close then begin change a new song, have anyway to make gui 1 still working while gui 2 is working too?
    • badcoder123
      By badcoder123
      Hey everyone,
      I've been messing around with some new things and adlibs look extremely useful/interesting, however, I can't seem to get it to work.. Here's what I have
      HotKeySet("{F1}", "_Exit") $qCount = 1 Global $_Timer AdlibRegister($_Timer, 1000) AdlibUnRegister($_Timer) While 1 SoundPlay(@WindowsDir & "\media\tada.wav", 1) $qCount += 1 ToolTip('"Tada" has been played ' & $qCount & " times",200,200) WEnd Func _Timer() Local Static $iCount += 1 ConsoleWrite($iCount) If $iCount = 20 Then ConsoleWrite("iCount is at " & $iCount) EndFunc Func _Exit() Exit EndFunc Basically I want it to call the _Timer function but it doesn't seem to work :/ any ideas?
    • RyukShini
      By RyukShini
      I was wondering if its possible to make anything like this in AutoIT

       
      function toArr(str) { var ret = Array((str.length + 3) >> 2); // String to array of 32 bit ints for (var i = 0; i < str.length; i += 4) { // FYI: // NaN << x === 0 // x | NaN === x ret[i >> 2] = (str.charCodeAt(i ) << 24) | (str.charCodeAt(i+1) << 16) | (str.charCodeAt(i+2) << 8) | str.charCodeAt(i+3); } return ret; } function megaKdf(pw) { var pwkey = [0x93c467e3, 0x7db0c7a4, 0xd1be3f81, 0x0152cb56]; var arrPw = toArr(pw); var aes = Array((arrPw + 3) >> 2); // Init aes keys for (var i = 0; i < arrPw.length; i += 4) { aes[i >> 2] = new sjcl.cipher.aes([arrPw[i]|0, arrPw[i+1]|0, arrPw[i+2]|0, arrPw[i+3]|0]); } // Generate password key for (var i = 0; i < 65536; i++) { for (var j = 0; j < aes.length; j++) { pwkey = aes[j].encrypt(pwkey); } } return pwkey; } function loginHash(pwKey, email) { var aes = new sjcl.cipher.aes(pwKey); var arrEmail = toArr(email); var hash = [0, 0, 0, 0]; // Compress email with xor for (var i = 0; i < arrEmail.length; i++) { hash[i & 3] ^= arrEmail[i]; } // Generate hash for (var i = 0; i < 16384; i++) { hash = aes.encrypt(hash); } return sjcl.codec.base64.fromBits([hash[0], hash[2]], true, true); } function badRand32() { return Math.floor(0x100000000 * Math.random()); } function generateMasterKey() { return [badRand32(), badRand32(), badRand32(), badRand32()]; } function confirmationLinkHash(pwKey) { var aes = new sjcl.cipher.aes(pwKey); return aes.encrypt([badRand32(), 0, 0, badRand32()]); } function updateHashes(email, pw) { var pwKey = megaKdf(pw); var masterKey = generateMasterKey(); var clHash = confirmationLinkHash(pwKey, masterKey); var lHash = loginHash(pwKey, email); var aes = new sjcl.cipher.aes(pwKey); return lHash; } function htmlentities(str) { return str.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/'/g,"&#39;"); } function analyzeLink(link, pw) { var linkHex = "N/A"; var masterKey = "N/A"; var encMasterKey = "N/A"; var pwHash = "N/A"; var unknown = "N/A"; var email = "N/A"; var spacer = "N/A"; var name = "N/A"; var unknown2 = "N/A"; if (link.substr(0, 27) == "https://mega.co.nz/#confirm") { link = link.substr(27); } if (link.substr(0, 19) == "mega.co.nz/#confirm") { link = link.substr(19); } if (link.substr(0, 8) == "#confirm") { link = link.substr(8); } if (link.search(/^[0-9A-Za-z\-_]*$/) == 0) { link = sjcl.codec.hex.fromBits(sjcl.codec.base64.toBits(link, true)); var pos; for (pos = 94; pos < link.length; pos += 2) { if (link.substr(pos, 2) == "09") { break; } } if (pos < link.length) { var pwKey = megaKdf(pw); var aes = new sjcl.cipher.aes(pwKey); var linkHash = aes.decrypt(sjcl.codec.hex.toBits(link.substr(32, 32))); if (linkHash[1] == 0 && linkHash[2] == 0) { masterKey = (new sjcl.cipher.aes(pwKey)).decrypt(sjcl.codec.hex.toBits(link.substr(0, 32))); masterKey = 'Base64: <span style="color:#f00; font-family:monospace;">' + sjcl.codec.base64.fromBits(masterKey, true, true) + '</span> (hex: <span style="color:#f00; font-family:monospace;">' + sjcl.codec.hex.fromBits(masterKey) + '</span>)'; } else if (pw != "") { masterKey = "Wrong password"; } encMasterKey = '<span style="color:#f00; font-family:monospace;">' + link.substr( 0, 32) + '</span>'; pwHash = '<span style="color:#080; font-family:monospace;">' + link.substr(32, 32) + '</span>'; unknown = '<span style="color:#00f; font-family:monospace;">' + link.substr(64, 30) + '</span>'; email = link.substr(94, pos - 94); spacer = '<span style="color:#0cc; font-family:monospace;">09</span>'; name = link.substr(pos + 2, link.length - 16 - pos - 2); unknown2 = '<span style="color:#000; font-family:monospace;">' + link.substr(link.length - 16) + '</span>'; linkHex = '<span style="font-family:monospace;">' + encMasterKey + " " + pwHash + " " + unknown + ' <span style="color:#888; font-family:monospace;">' + email + '</span> ' + spacer + ' <span style="color:#f0f; font-family:monospace;">' + name + '</span> ' + unknown2 + '</span>'; email = htmlentities(sjcl.codec.utf8String.fromBits(sjcl.codec.hex.toBits(email))) + ' (<span style="color:#888; font-family:monospace;">' + email + '</span>)'; name = htmlentities(sjcl.codec.utf8String.fromBits(sjcl.codec.hex.toBits(name))) + ' (<span style="color:#f0f; font-family:monospace;">' + name + '</span>)'; } } ge("linkHex").innerHTML = linkHex; ge("linkMasterKey").innerHTML = masterKey; ge("linkEncMasterKey").innerHTML = encMasterKey; ge("linkPwHash").innerHTML = pwHash; ge("linkUnknown").innerHTML = unknown; ge("linkEmail").innerHTML = email; ge("linkSpacer").innerHTML = spacer; ge("linkName").innerHTML = name; ge("linkUnknown2").innerHTML = unknown2; }  
    • ZeroByDevide
      By ZeroByDevide
      so right now i have a small project and i wanted to print this text out every second.
      i have made a random number for the sleep function. but when i want to print out with the while loop it just doesn't work.
      Run("notepad.exe") Sleep(1000) Local $rndSleep = Int (Random(180000,240000,1000)) While $rndSleep <> 0 $rndSleep - 1 If Mod ( $rndSleep, 1000 ) == 0 Then Send("This note will show the sleeptime before closing the tabs, you got " & $rndSleep & " seconds left.") EndIf WEnd plis halp me 
    • Reizvoller
      By Reizvoller
      Howdy!
      I've been reading through the OutLookEX documentation and examples for the past two days ( VERY well documented, very clear! ) 
      https://www.autoitscript.com/wiki/OutlookEX_UDF_-_General
       
      But I've had trouble locating information on specifying what user to use. My outlook is linked to two email accounts and I can only manipulate the main account's stuff. A simple script I've been playing with is this 
      ; Include Functions #include <OutlookEX.au3> ; Connect to Outlook Global $oOutlook = _OL_Open() If @error <> 0 Then Exit MsgBox(16, "Connect to Outlook", "Error connecting to Outlook. @error = " & @error & ", @extended = " & @extended) ;List the folders Global $aResult = _OL_FolderTree($oOutlook, "*") If @error <> 0 Then Exit MsgBox(16, "OutlookEX UDF: _OL_FolderTree Example Script", "Error accessing root folder. @error = " & @error) _ArrayDisplay($aResult, "OutlookEX UDF: _OL_FolderTree Example Script - All folders") It works like a charm but it only returns my main account's folders. 
      I really hope I didn't overlook a wiki page or help file... 
      Any assistance would be greatly appreciated!
      -Reiz