Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีค้นหา Substring ด้วย Regular Expression ใน C#

สตริงต้นฉบับ:

string str = " My make ";

Regular Expression หา "make":

@"\bmake\b"

ตัวอย่าง

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");
        }
    }
}

ผลลัพธ์

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