How to retrieve a part of filepath in one line?
I knew somebody would ask that... :-)
Frankly, I don't think it is a good idea to use REs here...
AHK's SplitPath uses a system call to do the split, and I assume it can handle all legal cases.
My code below, for example, doesn't handle UNC (\\serverName\path). I can add this, but this add even more complexity! And it is simpler to do two expressions, after checking if the string starts with a double backslash.
Just for fun, I made anyway an expression that should work on most canonical paths... And that's a good opportunity to introduce multiline expressions with comments! :-) So it is a bit more readable and self-documenting.
; Rotate or comment out these test values
somePath = \temp\install\FooSoft\config\templates\server\res\report_properties\
somePath = \temp\install\FooSoft\config\templates\server\res\report_properties
somePath = \temp\install\FooSoft\config\templates\server\res\report.properties
somePath = E:\temp\install\FooSoft\config\templates\server\res\report_properties\
somePath = E:\temp\install\FooSoft\config\templates\server\res\report_properties
somePath = E:\temp\install\FooSoft\config\templates\server\res\report.properties
# The drive, capture #1
# The path, capture # 2
(\\ # Probably starts with a backslash
(?:[^\\]+\\)* # A repeated sequence of non-backslash chars followed by a slash
# The file name, capture # 3
# If it has an no extension
# A sequence of non-dot chars, capture #4
# Or with extension
# A sequence of any chars, capture #5
# The extension dot
# The extension, made of at least one non-dot char, capture #6
splitResult := RegExMatch(somePath, re, "ix", splitted)
fileName := splitted3
dir := splitted2
extension := splitted6
nameNoExt := splitted4 . splitted5
drive := splitted1
The non-extended expression is:
I should suggest a feature that I saw nowhere up to now: since AutoHotkey handle named captures in replace strings, it could be cool to be able to specify an option telling it to transform these named captures to variables holding the capture! Thus, no need for the extra step of assigning array members to variables of more significant names.
Another way could be to add an option to return the nth capture instead of a found position. Seems more natural than using RegExReplace for this, as it constraints to match the remainder of the string to remove it.Goyyah
, I haven't exactly answered your request, but as advised, you might not want to use REs here. I give the above more for educational purpose than for practical purpose, as it is easy to find paths that make this RE choke.
You can create a function that does a SplitPath and returns the relevant part, that can be part of a standard library.
Wanting to save some lines at all costs might lead to overly complex code, hard to maintain, and that can break when not expected...