0

so kind of a small problem, but i find the Regex expressions very hard to understand, i've been trying to look for a solution to my problem.

So, i have a class where i handle File types by their ending extensions as such:

public static bool IsPythonFile(string pattern)
    {
        if (Regex.IsMatch(pattern, ".py$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".pyw$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".py3$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".pyi$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".pyx$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".py*$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".pyw*$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".py3*$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".pyi*$", RegexOptions.IgnoreCase) ||
            Regex.IsMatch(pattern, ".pyx*$", RegexOptions.IgnoreCase))
        {
            return true;
        }

        return false;
    }

So the '*' (star sign) that i'm trying to implement comes from a Tabcontrol, when Text_Changed is triggered, signifying that the file has been modified.

I want to include '.py' or '.py*' at the ending of the end of the Tabpage text, and i would want to return true in this bool. Does anybody know the pattern? Thanks for the help.

Kirtstar web
  • 147
  • 8
  • 1
    `.` and `*` are *special*. To match them as literal chars in a regex when outside of character classes, you need to prepend them with a literal ``\``. – Wiktor Stribiżew Jul 22 '20 at 14:23
  • @WiktorStribiżew So do you mean ".py*$\" will do? – Kirtstar web Jul 22 '20 at 14:25
  • To match `.py` at the end of string, use `@"\.py$"`. To match `.py*` at the end of string, use `@"\.py\*$"` – Wiktor Stribiżew Jul 22 '20 at 14:29
  • @WiktorStribiżew I think i understand now, thank you so much. – Kirtstar web Jul 22 '20 at 14:29
  • 1
    Alternatively you can use `Path.GetExtension` and just do a straight comparison like `Path.GetExtension(pattern) == ".py*"` (and then you could put the matches in a HashSet for a quick lookup) or even just use `string.EndsWith` like `pattern.EndsWith(".py*")`. Regular expressions are over kill for what you want IMHO, especially since you're doing 10 separate ones instead of attempting to combine them into one single regular expression comparison. – juharr Jul 22 '20 at 15:02
  • 1
    A single regular expression you could use instead would be `@"\.py[3ixw]?\*?$"`. Then it would just be `return Regex.IsMatch(pattern, @"\.py[3ixw]?\*?$", RegexOptions.IgnoreCase);` – juharr Jul 22 '20 at 15:07

0 Answers0