How to match strings using wildcards in C# and VB.NET

To match strings using wildcards in C# and VB.NET you can use the following snippet.
It will internally convert the wildcard string to a Regex.

The Console-Output of this sample will be:

C:\Test\myFile01.xml
C:\Test\myFile02.xml

Sample C#

#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

#endregion

namespace de.fesslersoft.RegexWildCard
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var fileList = new List<String>();
            fileList.Add(@"C:\Test\myFile01.xml");
            fileList.Add(@"C:\Test\myFile02.xml");
            fileList.Add(@"C:\Test\myFolder01.xml");
            fileList.Add(@"C:\Test\myFolder02.xml");

            var wildCard = new Wildcard("*File*.xml", RegexOptions.IgnoreCase);
            foreach (var file in fileList.Where(file => wildCard.IsMatch(file)))
            {
                Console.WriteLine(file);
            }
            Console.Read();
        }
    }


    public class Wildcard : Regex
    {
        public Wildcard(string pattern) : base(ToRegex(pattern))
        {
        }

        public Wildcard(string pattern, RegexOptions options) : base(ToRegex(pattern), options)
        {
        }

        public static string ToRegex(string pattern)
        {
            return "^" + Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
        }
    }
}

Sample VB.NET (autoconverted)

#Region ""

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text.RegularExpressions

#End Region

Namespace de.fesslersoft.RegexWildCard
	Friend Class Program
		Private Shared Sub Main(args As String())
			Dim fileList = New List(Of [String])()
			fileList.Add("C:\Test\myFile01.xml")
			fileList.Add("C:\Test\myFile02.xml")
			fileList.Add("C:\Test\myFolder01.xml")
			fileList.Add("C:\Test\myFolder02.xml")

			Dim wildCard = New Wildcard("*File*.xml", RegexOptions.IgnoreCase)
			For Each file As var In fileList.Where(Function(file) wildCard.IsMatch(file))
				Console.WriteLine(file)
			Next
			Console.Read()
		End Sub
	End Class


	Public Class Wildcard
		Inherits Regex
		Public Sub New(pattern As String)
			MyBase.New(ToRegex(pattern))
		End Sub

		Public Sub New(pattern As String, options As RegexOptions)
			MyBase.New(ToRegex(pattern), options)
		End Sub

		Public Shared Function ToRegex(pattern As String) As String
			Return "^" + Escape(pattern).Replace("\*", ".*").Replace("\?", ".") + "$"
		End Function
	End Class
End Namespace

Please Share us:
Please rate this snippet

Leave a Reply