Wikis / Unreal Wiki / Legacy:MaskedCompare

With the algoritm below you can compare a string with a wild card string.

Usage

There are two types of wild cards: * to match zero or more characters and ? to match a single character

For example, the mask bite my *ass matches:

bite my ass
bite my shining metal ass
bite my          ass

The mask mich?el matches:

michael
michiel

But not:

michel
michaeel

Code

// Internal function used for MaskedCompare
static private final function bool _match(out string mask, out string target)
{
  local string m, mp, cp;
  m = Left(mask, 1);
  while ((target != "") && (m != "*"))
  {
    if ((m != Left(target, 1)) && (m != "?")) return false;
    mask = Mid(Mask, 1);
    target = Mid(target, 1);
		m = Left(mask, 1);
  }
 
  while (target != "") 
  {
		if (m == "*") 
    {
      mask = Mid(Mask, 1);
			if (mask == "") return true; // only "*" mask -> always true
			mp = mask;
			cp = Mid(target, 1);
      m = Left(mask, 1);
		} 
    else if ((m == Left(target, 1)) || (m == "?")) 
    {
			mask = Mid(Mask, 1);
      target = Mid(target, 1);
  		m = Left(mask, 1);
		} 
    else 
    {
			mask = mp;
      m = Left(mask, 1);
			target = cp;
      cp = Mid(cp, 1);
		}
	}
 
  while (Left(mask, 1) == "*") 
  {
		mask = Mid(Mask, 1);
	}
	return (mask == "");
}
 
// Compare a string with a mask
// Wildcards: * = X chars; ? = 1 char
// Wildcards can appear anywhere in the mask
static final function bool MaskedCompare(coerce string target, string mask, optional bool casesensitive)
{
  if (!casesensitive)
  {
    mask = Caps(mask);
    target = Caps(target);
  }
  if (mask == "*") return true;
 
  return _match(mask, target);
}

CategoriesPage Categories

Info Page Information

2022-11-18T09:48:38.171152Z 2005-01-14T03:28:59Z Foxpaw revert https://wiki.beyondunreal.com/Legacy:MaskedCompare Attribution-NonCommercial-ShareAlike 3.0