Page 1 of 1

Converting wildcards to RegEx criteria with Wildcards2RegEx()

Posted: 19 Nov 2020, 16:30
by JnLlnd
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.

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$"
}
;---------------------------------------------------------

Re: Converting wildcards to RegEx criteria with Wildcards2RegEx()

Posted: 19 Nov 2020, 17:21
by JnLlnd
I edit the function to add the "i)" option making the RegEx criteria case-insensitive as are DOS wildcards.

Re: Converting wildcards to RegEx criteria with Wildcards2RegEx()

Posted: 20 Nov 2020, 01:25
by daywalker
Hi,

nice idea, which I can use, but when using strWildcards := "????.*" only list files with 4 characters, but in DOS dir ????.* will display all files with 0-4 characters before the dot. So I think "?" should be replaced with "\E.?\Q" if you want to be DOS compliant:

Code: Select all

;---------------------------------------------------------
Wildcards2RegEx(strDosWildcards)
;---------------------------------------------------------
{
	return "i)^\Q" . StrReplace(StrReplace(StrReplace(strDosWildcards, "\E", "\E\\E\Q"), "?", "\E.?\Q"), "*", "\E.*\Q") . "\E$"
}

Re: Converting wildcards to RegEx criteria with Wildcards2RegEx()

Posted: 20 Nov 2020, 08:56
by JnLlnd
Thank you, daywalker. I'll edit the original post.