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

Quantifiers ใน C# Regular Expressions

Quantifiers (ตัวกำหนดปริมาณ) ใน Regular Expressions ใช้ระบุจำนวนครั้งที่องค์ประกอบก่อนหน้า (อักขระ, กลุ่ม, หรือคลาสอักขระ) ต้องปรากฏในสตริงนำเข้าเพื่อให้ถือว่า match

ตาราง Quantifiers ทั้งหมดใน C#

Quantifier คำอธิบาย Pattern ตัวอย่าง Match ตัวอย่าง
* Match องค์ประกอบก่อนหน้า 0 ครั้งหรือมากกว่า \d*\.\d ".0", "19.9", "219.9"
+ Match องค์ประกอบก่อนหน้า 1 ครั้งหรือมากกว่า be+ "bee" ใน "been", "be" ใน "bent"
? Match องค์ประกอบก่อนหน้า 0 หรือ 1 ครั้ง rai?n "ran", "rain"
{n} Match องค์ประกอบก่อนหน้าถูกต้อง n ครั้ง ,\d{3} ",043" ใน "1,043.6"
{n,} Match องค์ประกอบก่อนหน้าอย่างน้อย n ครั้ง \d{2,} "166", "29", "1930"
{n,m} Match องค์ประกอบก่อนหน้าอย่างน้อย n ครั้ง แต่ไม่เกิน m ครั้ง \d{3,5} "166", "17668", "19302" ใน "193024"

Lazy Quantifiers (Non-greedy) - Match น้อยที่สุดเท่าที่จะเป็นไปได้

Quantifier คำอธิบาย Pattern ตัวอย่าง Match ตัวอย่าง
*? Match 0 ครั้งหรือมากกว่า แบบ lazy \d*?\.\d ".0", "19.9", "219.9"
+? Match 1 ครั้งหรือมากกว่า แบบ lazy be+? "be" ใน "been", "be" ใน "bent"
?? Match 0 หรือ 1 ครั้ง แบบ lazy rai??n "ran", "rain"
{n}? Match ถูกต้อง n ครั้ง แบบ lazy ,\d{3}? ",043" ใน "1,043.6"
{n,}? Match อย่างน้อย n ครั้ง แบบ lazy \d{2,}? "166", "29", "1930"
{n,m}? Match ระหว่าง n ถึง m ครั้ง แบบ lazy \d{3,5}? "166", "17668", "193", "024" ใน "193024"

ความแตกต่าง Greedy vs Lazy

string input = "<div>Hello</div><div>World</div>";

// Greedy (default) - match มากที่สุด
Regex greedy = new Regex("<.*>");  
// Match: "<div>Hello</div><div>World</div>" (ทั้งสตริง)

// Lazy - match น้อยที่สุด
Regex lazy = new Regex("<.*?>");  
// Match: "<div>", "</div>", "<div>", "</div>" (แท็กแต่ละอัน)

ตัวอย่างการใช้งานจริง

using System;
using System.Text.RegularExpressions;

public class Demo {
    public static void Main() {
        string text = "Order 123, 4567, 89 items";
        
        // หาตัวเลข 3-5 หลัก
        MatchCollection matches = Regex.Matches(text, @"\d{3,5}");
        
        foreach (Match m in matches) {
            Console.WriteLine($"Found: {m.Value} at index {m.Index}");
        }
    }
}

ผลลัพธ์

Found: 4567 at index 8
Found: 123 at index 6