Jump to content
Sign in to follow this  
Mecano

Regex - Drive letter - ellipses - two last folders from path

Recommended Posts

Mecano

Hallo Members,

I'm looking for a good regex to get the drive letter and the last two folders from a file path,

If the path is to long for the label width then show drive +   ellipses and two last folders.

Drive:\(ellipses)\folder\folder

ex. D:\...\folder\folder

and when the folder is in the root of the drive then show D:\Folder


The test GUI

#cs ----------------------------------------------------------------------------

 AutoIt Version: 3.3.12.0
 Author:         Mecano

 Script Function: ELLIPSIS
        Long path:   Drive:\...\Folder\Folder
           if root then Drive:\Folder

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here
$sFile = "F:\Just a folder\in a another folder\and another\This-dir\And-this-dir"
$EllipsisPath = StringRegExpReplace($sFile, '\w[a-zA-Z \\]+\\', '') ; <- This needs another regex

;no ellipsis needed, for testing purposes only 
$sUSB = "K:\Just a folder"
$PathforUSB = StringRegExpReplace($sUSB, '\w[a-zA-Z \\]+\\', '')

#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
$Form1 = GUICreate("Drive + Two last folders of path", 327, 236, 192, 124)
$Button1 = GUICtrlCreateButton("Test label", 40, 168, 97, 33)
$Label1 = GUICtrlCreateLabel("F:\...\This-dir\And-this-dir", 40, 12, 200, 40) ; <- Looks good but not dynamic
GUICtrlSetColor($Label1, 32768)
$Label2 = GUICtrlCreateLabel($sFile, 40, 40, 200, 40,  $DT_END_ELLIPSIS) ; <- not the last two directorys
GUICtrlSetColor($Label2, 16711680)
$Label3 = GUICtrlCreateLabel("Var label1", 40, 72, 200, 40)
GUICtrlSetColor($Label3, 16711680)
$Label4 = GUICtrlCreateLabel("Var label", 40, 104, 200, 40)
GUICtrlSetColor($Label4, 16711680)
GUISetState(@SW_SHOW)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $Button1
            GUICtrlSetData($Label3, $EllipsisPath) ; $DT_END_ELLIPSIS <- works only on GUICtrlCreateLabel
            GUICtrlSetData($Label4, $PathforUSB) 

    EndSwitch
WEnd

 

 

Thanks in advance

 

 

Share this post


Link to post
Share on other sites
mikell
$sFile1 = "F:\Just a folder\in a another folder\and another\This-dir\And-this-dir"
$sFile2 = "G:\This-dir\And-this-dir\"   ; final "\" optional
$sFile3 = "K:\Just a folder"

Msgbox(0,"", _ShortPath($sFile1) & @crlf & _ShortPath($sFile2) & @crlf & _ShortPath($sFile3) )

Func _ShortPath($path)
   Return StringRegExpReplace($path, '^\w:\\\K.*(?=\\[^\\]+\\[^\\]+\\?$)', "...")
EndFunc

:)

Share this post


Link to post
Share on other sites
iamtheky

and without regex

$sFile1 = "F:\Just a folder\in a another folder\and another\This-dir\And-this-dir"
;~ $sFile1 = "G:\This-dir\And-this-dir\"   ; final "\" optional
;~ $sFile1 = "K:\Just a folder"



$sOut = ubound(stringsplit($sFile1 , "\" , 2)) > 4 ? stringleft($sFile1 , 3) & "...\" & stringreverse(stringsplit(stringreverse($sFile1) , "\" , 2)[0] & "\" & stringsplit(stringreverse($sFile1) , "\" , 2)[1]) : $sFile1

msgbox(0, '' , $sOut)

 


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites
Mecano

Oh Yeah, mikell you saved my day again :)

boththose, thanks for your contribution, but I need the regex

Big thanks for the solution.

Share this post


Link to post
Share on other sites
guinness

boththose, thanks for your contribution, but I need the regex

Why so? Is it to show off to your coding buddies?

Though the native version could be improved a little bit and the regex version is alot neater, using native string functions doesn't necessarily mean bad programming. So please enlighten me, why do you need a regex version? What is your reason or thought process as to why that is?

Edited by guinness

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

Share this post


Link to post
Share on other sites
mikell

boththose,
StringSplit is not a handy way to manage an optional final "\" (i.e. your code fails on "G:\test\This-dir\And-this-dir\" )
Assuming that this final "\" does not exist, StringSplit works nice but it's much better to call it only once

$sFile1 = "F:\Just a folder\in a another folder\and another\This-dir\And-this-dir"
$sFile2 = "G:\test\This-dir\And-this-dir"
$sFile3 = "K:\Just a folder"

Msgbox(0,"", _ShortPath($sFile1) & @crlf & _ShortPath($sFile2) & @crlf & _ShortPath($sFile3) )

Func _ShortPath($path)
   Local $tmp = StringSplit($path, "\")
   Return ($tmp[0] > 3) ? ($tmp[1] & "\...\" & $tmp[$tmp[0]-1] & "\"  & $tmp[$tmp[0]]) : $path
EndFunc

 

Share this post


Link to post
Share on other sites
iamtheky

you gave your edge case both option and finality?   As you evidenced, I also didnt really need to flip it around and take it from behind..... but the ladies love it.


,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites
Mecano


@guinness,

"Though the native version could be improved a little bit and the regex version is alot neater"

I totally agree with that

"Why so? Is it to show off to your coding buddies?"

Not at all, just want to learn regex and try to understand the regex
I was practicing regex and get stuck, I'm not a regex guru

this was no variable enough:

$FullPath    = "F:\Just a folder\in a another folder\and another\This-dir\And-this-dir"
$StringLeft  = StringLeft($FullPath, 2)
$StringRight = StringRight($FullPath, 21);
MsgBox(0, "ShortPath", $StringLeft & "\...\" & $StringRight)

So searching for examples I found this topic https://www.autoitscript.com/forum/topic/166301-short-path-anywhere-at-the-string/?do=findComment&comment=1214608

$string = 'regedit.exe /e:a "D:\data\backup\laptop\CCleaner\CCleaner.reg" "HKEY_CURRENT_USER\Software\Piriform\CCleaner"'
$short = StringRegExpReplace($string, '("[^\\]+\\)(?:[^\\"]+\\)*([^"]+")', "$1...\\$2")
ConsoleWrite($short)

Tried to understand the regex, thats why I wrote "you saved my day"

K.* was something new for me

http://www.regular-expressions.info/keep.html

 

 

Share this post


Link to post
Share on other sites
mikell

Oh you are learning ! Sorry, here are the comments :

'^\w:\\\K.*(?=\\[^\\]+\\[^\\]+\\?$)'

^        : beginning of string
\w:\\    : a word char + colon + antislash
\K       : escape sequence meaning 'forget what you've seen before'
.*       : the part to replace
(?=      : lookahead 'followed by'
\\[^\\]+  : antislash + one or more non-antislash char. Used twice 
\\?      : the optional final antislash
$        : end of string

:)

Share this post


Link to post
Share on other sites
Mecano

mikell, good explanation, as I wrote earlier \K is something new for me. :D

With this fantastic forum and for example SRETester I learn every time something new.

Next thing is improve my skills with AutoIt/Microsoft.XML DOM like jdelaney wrote

:bye:

 

 

Share this post


Link to post
Share on other sites
guinness

@Mecano, fair enough with the explanation.


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

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  

  • Similar Content

    • gruntydatsun
      By gruntydatsun
      I have an XML file and every time there are three lines in a row with only <null/> in them, i want to insert a fourth line with <null/>.   Each line starts with 3 white spaces, followed by <null/> and ends with a white space followed by CR LF.   The presence of the three lines as described is unique to the points where I want to insert a line in this document.
       I'm trying to figure out how to apply the repeating part of a regex  {1,4} but apply it to this whole segment. 
      So far I have the below which picks up an individual line ok:
      ^\s{3}<null/>\s\r\n I tried wrapping it all in braces () then adding {3} but I'm obviously getting something wrong. 
      Attached is a section from the xml file with a block of nulls that should be matched if anyone would like to have a look.
      Help_From_Forum.xml
    • WoodGrain
      By WoodGrain
      Hi guys,
      I'm learning about GUI's, I'm trying the below code, the idea being if I press the letter "e" while I have the GUI open I want the label color to change to green (I'm using a UDF for label colors). But every time I press "e" on my keyboard I just get a "ding" sound from my speakers and nothing changes with the label.
      I've looked at using something like "While GUIGetMsg() <> $GUI_EVENT_CLOSE" as I've seen it in other code instead of "While 1", but I don't think it's relevant.
      #include <GUIConstantsEx.au3>; for GUI... #include <GUIRichLabel.au3>; UDF for rich text label fonts #include <Misc.au3>; for _IsPressed $myLetter = "e" $hGUI = GUICreate("test", 700, 60) $lbl2 = _GUICtrlRichLabel_Create($hGUI, '<font color="purple">' & $myLetter & '</font>', 10, 10); , 260, 25 GUISetState(@SW_SHOW) Local $hDLL = DllOpen("user32.dll") While 1 if _IsPressed(Hex($myLetter), $hDLL) Then While _IsPressed(Hex($myLetter), $hDLL) Sleep(250) WEnd _GUICtrlRichLabel_SetData($lbl2, '<font color="green">' & $myLetter & '</font>') Sleep(2000) DllClose($hDLL) Exit EndIf Sleep(50) WEnd DllClose($hDLL) I am using an array of letters that I'm wanting to do this for, but as I can't get it to work I've stripped it down to the simplest code I can think of to try and get this working first. Appreciate any help.
      Thanks!
    • milkmoron
      By milkmoron
      I am trying to search in a web browser dates XX/XX/XXXX that are also links. I want to click them after and remove them from the array. This is all I have so far. Nothing shows up. What am I doing wrong?
      ControlFocus ("Customer Center", "", "")
      Local $aArray = StringRegExp('(..)/(..)/(....)', '(..)/(..)/(....)', $STR_REGEXPARRAYFULLMATCH)
      For $i = 0 To UBound($aArray) - 1
          MsgBox($MB_SYSTEMMODAL, "RegExp Test with Option 2 - " & $i, $aArray[$i])
      Next
       
    • luckyluke
      By luckyluke
      $t = '... 1-347-318-9643 1-347-318-9647 1-347-318-9648 1-347-318-9650 1-347-318-9651 1-347-318-9652 1-347-318-9653 1-347-318-9655 1-347-318-&nbsp;...' $pattern = '347.*?318.*?9655' $tmp = StringRegExpReplace($t, $pattern, "|||", 1) ConsoleWrite($tmp & @CRLF) However i got this output:
      ... 1-|||  1-347-318-&nbsp;...
      Why i got only that, where is the other string, i thought the output should be this:
      ... 1-347-318-9643  1-347-318-9647  1-347-318-9648  1-347-318-9650  1-347-318-9651  1-347-318-9652  1-347-318-9653  1-|||  1-347-318-&nbsp;...
    • TheSaint
      By TheSaint
      Files Checklist
      Just a simple little (complex enough) program I whipped up, for a purpose ... but only too happy to share.
      It can of course be modified to do more, but at the moment just compares file names with or without path ... Location versus Checklist.
      There are of course other compare programs out there, most doing a lot more than mine (i.e. WinMerge or FileComparer). But I wanted something quick and simple with drag & drop, that uses up a smallish amount of screen real estate.
      NOTE - The SAVE button is also a LOAD one, and displays 'Load' when the list is empty. So you can save and load specific lists. While in SAVE mode, the button can also be used with CTRL held down, to ADD another list to existing (displayed one) ... combining as they say ... though not saved until you SAVE. CLEAR button removes a selected entry, or if used with CTRL held down, queries about removing all listed entries.
              
      Files Checklist v1.2.zip
      Files Checklist v1.3.zip
      Files Checklist v1.4.zip  (Includes a BUGFIX.)
        (source included)
      WARNING - While this program does not act on files or folders ADDED or CHECKED, you might act on the results, so I advise caution, and I also recommend using the new 'Relative' option in v1.3 or newer ... but you still need to understand what you are doing and what the results actually mean. Some basic examples in the next post.
      Enjoy!
      RELATED
      Users might also be interested in another somewhat related program of mine.
      DeleteIf Same
      Cheers!
×