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

การจับคู่สตริงด้วยตัวแทน (Wildcard) ใน C#

ตัวอักษรตัวแทน (Wildcard) ที่ใช้บ่อยที่สุดคือดอกจัน (*) ซึ่งแทนศูนย์หรืออักขระมากกว่าหนึ่งอักขระในสตริง

ตัวอย่าง

ในตัวอย่างต่อไปนี้ ใช้ดอกจันเพื่อจับคู่คำที่ขึ้นต้นด้วย 't' และลงท้ายด้วย 's':

@"\bt\S*s\b"

โค้ดเต็ม

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

ผลลัพธ์

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