ircsharp/IRCRobots/Glob.cs

68 lines
1.7 KiB
C#

using System.Text;
namespace IRCRobots
{
public class Glob
{
public string Pattern { get; set; }
public static string Collapse(string pattern)
{
var result = new StringBuilder();
var i = 0;
while (i < pattern.Length)
{
var seenAst = false;
while (i < pattern.Length && (pattern[i] == '*' || pattern[i] == '?'))
{
if (pattern[i] == '?') result.Append('?');
else if (pattern[i] == '*') seenAst = true;
i++;
}
if (seenAst) result.Append('*');
if (i < pattern.Length) result.Append(pattern[i++]);
}
return result.ToString();
}
public bool Match(string s)
{
int i = 0, j = 0;
int iBackup = -1, jBackup = -1;
while (j < s.Length)
{
// p = (pattern[i:] or [None])[0]
var p = Pattern[i];
if (p == '*')
{
i++;
iBackup = i;
jBackup = j;
}
else if (p == '?' || p == s[j])
{
i++;
j++;
}
else
{
if (iBackup == -1)
return false;
jBackup++;
j = jBackup;
i = iBackup;
}
}
return i == Pattern.Length;
}
}
}