ใช้เมธอด exec() ของ RegExp เพื่อค้นหาและเข้าถึง Capture Groups (กลุ่มที่จับได้) ผลลัพธ์จะเป็นอาร์เรย์ ที่ index 0 คือ full match, index 1+ คือแต่ละ capture group
ตัวอย่าง
<html>
<head>
<script>
var str = "Username akdg_amit";
// (?:^|\s) = non-capturing group เริ่มบรรทัดหรือ whitespace
// akdg_ = literal
// (.*?) = capture group 1 (lazy match)
// (?:\s|$) = non-capturing group จบด้วย whitespace หรือจบสตริง
var myReg = /(?:^|\s)akdg_(.*?)(?:\s|$)/g;
var res = myReg.exec(str);
document.write(res[1]); // แสดง "amit"
</script>
</head>
<body>
</body>
</html>
ผลลัพธ์
amit
รายละเอียดผลลัพธ์ของ exec()
var str = "Username akdg_amit"; var regex = /(?:^|\s)akdg_(.*?)(?:\s|$)/g; var match = regex.exec(str); console.log(match[0]); // " akdg_amit" (full match) console.log(match[1]); // "amit" (capture group 1) console.log(match.index); // 9 (ตำแหน่งเริ่มต้น) console.log(match.input); // "Username akdg_amit" (สตริงต้นฉบับ)
เมธอดอื่นๆ สำหรับ Capture Groups
// 1. String.match() - ไม่มี g flag "abc123".match(/(\d+)/); // ["123", "123", index: 3, input: "abc123", groups: undefined] // 2. String.matchAll() (ES2020) - มี g flag, คืน iterator [... "a1b2c3".matchAll(/(\d)/g)]; // [["1","1"], ["2","2"], ["3","3"]] // 3. String.replace() กับฟังก์ชัน "a1b2".replace(/(\d)/g, (match, g1) => g1 + "!"); // "a1!b2!" // 4. Named Capture Groups (ES2018) const re = /(?\d{4})-(? \d{2})/; re.exec("2023-12").groups; // { year: "2023", month: "12" }
หมายเหตุ: ใช้ ?: เพื่อสร้าง Non-capturing Group (ไม่นับเป็น capture group)