Matching strings with a wildcard in C#


Commonly used wildcard characters are the asterisk (*). It represents zero or more characters in a string of characters.

In the following example asterisk is used to match words that begins with m and ends with e −

@”\bt\S*s\b”

The following is the complete code −

Example

 Live Demo

using System;
using System.Text.RegularExpressions;

namespace Demo {
   public class Program {
      private static void showMatch(string text, string expr) {
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      public static void Main(string[] args) {
         string str = "toss cross tacos texas";
         Console.WriteLine("Matching words that start with 't' and ends with 's':");
         showMatch(str, @"\bt\S*s\b");
      }
   }
}

Output

Matching words that start with 't' and ends with 's':
toss
tacos
texas

Updated on: 22-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements