นิพจน์ทั่วไปเป็นรูปแบบที่สามารถจับคู่กับข้อความที่ป้อนได้ รูปแบบประกอบด้วยตัวอักษร ตัวดำเนินการ หรือโครงสร้างตั้งแต่หนึ่งตัวขึ้นไป
เรามาดูตัวอย่างการแสดงคำที่ขึ้นต้นด้วยตัวอักษร 'M' โดยใช้ Regex
ตัวอย่าง
using System;
using System.Text.RegularExpressions;
namespace Demo {
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(m);
}
}
static void Main(string[] args) {
string str = "Mandatory requirements for a Cricket Match Event!";
Console.WriteLine("Matching words that start with 'M': ");
showMatch(str, @"\bM\S*");
Console.ReadKey();
}
}
} ผลลัพธ์
Matching words that start with 'M': The Expression: \bM\S* Mandatory Match
ข้างบนมีสตริงค่ะ
string str = "Mandatory requirements for a Cricket Match Event!";
เพื่อให้ได้คำทั้งหมดที่ขึ้นต้นด้วย 'M' ฉันได้ใช้รูปแบบต่อไปนี้ -
@"\bM\S*