Code for Wildcards

Discussions about Coding and Scripting
Post Reply
User avatar
Barbie
Godlike
Posts: 2808
Joined: Fri Sep 25, 2015 9:01 pm
Location: moved without proper hashing

Code for Wildcards

Post by Barbie »

In order not to reinvent the wheel I'm looking for UScript code that supports the wildcards ''*' and '?', maybe even with "greedy"-flag? Please no solutions that simply does an InStr() with one given token.
"Multiple exclamation marks," he went on, shaking his head, "are a sure sign of a diseased mind." --Terry Pratchett
User avatar
Feralidragon
Godlike
Posts: 5493
Joined: Wed Feb 27, 2008 6:24 pm
Personal rank: Work In Progress
Location: Liandri

Re: Code for Wildcards

Post by Feralidragon »

I have a function for exactly that in NW3, however quick disclaimer: I did this over 10 years ago, so it's very likely that it can be optimized/improved (especially since it seems to be recursive, something I would likely not do nowadays).

Here you go ("sA" is the wildcard, should have made the function more clear on that back then):

Code: Select all

//Check if string sA matches sB (having sA with wildcards like * and ?)
static function bool StrMatch(string sA, string sB, optional bool bCaseSensitive)
{
local int wildPos, curI, curJ, w;
local string subStr1, subStr2;

	if (sA == "*")
		return True;

	if (!bCaseSensitive)
	{
		sA = Caps(sA);
		sB = Caps(sB);
	}
	
	wildPos = InStr(sA, "?");
	if (wildPos >= 0)
	{
		subStr1 = Left(sA, wildPos);
		subStr2 = Left(sB, wildPos);
		if (subStr1 != subStr2)
			return False;
		return static.StrMatch(Mid(sA, wildPos + 1), Mid(sB, wildPos + 1), bCaseSensitive);
	}
	
	wildPos = InStr(sA, "*");
	if (wildPos >= 0)
	{
		subStr1 = Left(sA, wildPos);
		subStr2 = Left(sB, wildPos);
		if (subStr1 != subStr2)
			return False;
		
		subStr1 = Mid(sA, wildPos + 1);
		subStr2 = Mid(sB, wildPos);
		if (subStr1 == "")
			return True;
		
		curI = Len(subStr1);
		w = InStr(subStr1, "*");
		if (w >= 0)
			curI = Min(w, curI);
		w = InStr(subStr1, "?");
		if (w >= 0)
			curI = Min(w, curI);
		curJ = InStr(subStr2, Mid(subStr1, 0, curI));
		if (curJ < 0)
			return False;
		return static.StrMatch(Mid(subStr1, curI), Mid(subStr2, curJ + curI), bCaseSensitive);
	}
	
	return (sA == sB);
}
Post Reply