Converting wildcards to RegEx criteria with Wildcards2RegEx()
Posted: 19 Nov 2020, 16:30
Regex expressions can be intimidating for non-programmers (and even for programmers!). In Quick Access Popup, I wanted to allow end users to filter a list of files (coming from a database) using the old DOS wildcards * and ? that most users are familiar with. But I could not find how to filter a list using these DOS wildcards in AHK. The solution would be to convert these wildcards (like the simple "*.mp3" or the more complex "abc??.m*") to a criteria that could be used with RegExMatch().
I asked the group of users attending the last AutoHotkey webinar (hosted monthly by @Joe Glines and Jackie Sztuk/@BlackHolyMan) if someone knew a function that would do it. These webinars are great! The solution to this problem did not exist before this webinar (as far as we knew) but it was resolved "live" during the webinar! Thanks to Jackie, @GeekDude, Dimitri Geerts and Jesús Prieto for their help with this.
The final version came from GeekDude. For those who would have a similar need, here is the function and an example script.
I asked the group of users attending the last AutoHotkey webinar (hosted monthly by @Joe Glines and Jackie Sztuk/@BlackHolyMan) if someone knew a function that would do it. These webinars are great! The solution to this problem did not exist before this webinar (as far as we knew) but it was resolved "live" during the webinar! Thanks to Jackie, @GeekDude, Dimitri Geerts and Jesús Prieto for their help with this.
The final version came from GeekDude. For those who would have a similar need, here is the function and an example script.
Code: Select all
#SingleInstance Force
strFiles := "abc.docx|abc.xlsx|def.docx|docx.txt"
strWildcards := "*.docx|abc.*|*b*.*|*.*x*|???.*|?b?.*o*|*c.*"
loop, parse, strWildcards, |
{
strWildCard := A_LoopField
strResult .= strWildCard . "`n"
loop, parse, strFiles, |
strResult .= A_LoopField . " -> " . (RegExMatch(A_LoopField, Wildcards2RegEx(strWildcard)) ? "yes" : "no") . "`n"
strResult .= "`n`n"
}
MsgBox, % strResult
return
;---------------------------------------------------------
Wildcards2RegEx(strDosWildcards)
;---------------------------------------------------------
{
return "i)^\Q" . StrReplace(StrReplace(StrReplace(strDosWildcards, "\E", "\E\\E\Q"), "?", "\E.?\Q"), "*", "\E.*\Q") . "\E$"
}
;---------------------------------------------------------