I search for solutions in this order: Past Code, Unreal Source, Wiki, BUF, groups.yahoo, google, screaming at monitor. – RegularX

Legacy:MaskedCompare

From Unreal Wiki, The Unreal Engine Documentation Site
Jump to: navigation, search

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

Usage[edit]

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[edit]

// 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);
}