How to find a matching substring using regular expression in C#?


Our string is −

string str = " My make ";

Use the following regular expression to find the substring “make”

@"\bmake\b"

Here is the complete code −

Example

Live Demo

using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   public class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);

         foreach(Match m in mc) {
            Console.WriteLine("Found:" + m);
         }
      }

      public static void Main(string[] args) {
         string str = "My make";

         Console.WriteLine("Matching words start with 'm' and ends with 'e':");
         showMatch(str, @"\bmake\b");
      }
   }
}

Output

Matching words start with 'm' and ends with 'e':
The Expression: \bmake\b
Found:make

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements