C#: Match text pattern using both question mark and asteriks

moondaddy 916 Reputation points
2022-04-30T21:10:40.88+00:00

Using C# 4.8, I need to loop through a list of strings and identify matches based on a patter. So for it's mostly working for example, these work:

string filter = "?MyFileName.txt"
or
string filter = "*FileName.txt"
or
string filter = "File"

string searchText = "zMyFileName.txt"

But this does not:

string filter = "?My*"

this is my regular expression:
private static String WildCardAndQuestionMarkToRegular(String value)
{
return "^" + Regex.Escape(value).Replace("\?", ".").Replace("\*", ".*") + "$";
}

bool foundMatch = Regex.IsMatch(searchText , WildCardAndQuestionMarkToRegular(filter), RegexOptions.IgnoreCase);

Any advise on how to make it find: "?My*"

Thank you

Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-05-01T00:54:56.967+00:00

    You can using globbing if you are reading these files from disk, the patterns are robust. I have code sample but only with .NET Core.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.