ใช้ Regular Expression \b\w หรือ \b[a-zA-Z] เพื่อจับตัวอักษรแรกของแต่ละคำ (Word Boundary)
Pattern อธิบาย
\b= Word Boundary (ตำแหน่งระหว่าง Word Char และ Non-Word Char)\w= Word Character [a-zA-Z0-9_][a-zA-Z]= ตัวอักษรอังกฤษเท่านั้น (ไม่รวมตัวเลข/Underscore)
ตัวอย่างโค้ด
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string str = "The Shape of Water got an Oscar Award!";
// Pattern: ตัวอักษรแรกของแต่ละคำ (เฉพาะ a-zA-Z)
string pattern = @"\b[a-zA-Z]";
MatchCollection matches = Regex.Matches(str, pattern);
Console.WriteLine("First letters:");
foreach (Match m in matches)
Console.Write(m.Value + " ");
Console.WriteLine(); // T S o W g a O A
}
}
ผลลัพธ์
First letters:
T S o W g a O A
Pattern Variations
| Pattern | Match | ตัวอย่าง Input | Output |
|---|---|---|---|
\b\w | Word char แรก (รวมตัวเลข/_) | "C# 123 Test" | C 1 T |
\b[a-zA-Z] | ตัวอักษรแรกเฉพาะ | "C# 123 Test" | C T |
\b\p{L} | Unicode Letter (รองรับไทย/จีน) | "สวัสดี World" | ส W |
(?<=\s|^)\w | หลัง Space หรือต้นสตริง | "Hello World" | H W |
สร้าง Acronym ด้วย Regex
public static string GetAcronym(string input)
{
if (string.IsNullOrWhiteSpace(input)) return "";
var matches = Regex.Matches(input, @"\b\p{L}");
return string.Concat(matches.Cast().Select(m => m.Value.ToUpper()));
}
// ทดสอบ
GetAcronym("Central Processing Unit") // "CPU"
GetAcronym("HyperText Markup Language") // "HTML"
GetAcronym("สถาบันเทคโนโลยี") // "สต"
Performance: Regex vs Split
// Regex: Slower (Compilation + Matching overhead)
// Split: Faster for simple cases
// Pre-compile Regex for reuse
private static readonly Regex FirstLetterRegex = new Regex(@"\b\p{L}", RegexOptions.Compiled);
public static string GetInitialsFast(string input)
{
return string.Concat(FirstLetterRegex.Matches(input).Cast().Select(m => m.Value));
}
กรณีใช้งานจริง
- สร้าง Acronym จากชื่อองค์กร/โครงการ
- Text Analysis: Feature Extraction
- Validation: ตรวจสอบรูปแบบรหัสที่ขึ้นต้นด้วยตัวอักษร
- Natural Language Processing: Tokenization เริ่มต้น